Don't just DRY your code, DRY your tests too!
I’m a big fan of having small classes. I’m not a big fan of having huge specs for a small class/object. Every time I see an opportunity to DRY my specs, I take it.
Today I wrote a spec to make sure that we gracefully ignore SPAMmy contact requests in the Ombu Labs contact page. It initially looked like this:
test "gracefully ignores spammy requests with valid attributes" do
@valid_contact = contacts(:two)
attributes = @valid_contact.attributes
.merge(email_confirmation: @valid_contact.email)
assert_no_difference("Contact.count") do
post :create, contact: attributes, format: 'js'
end
assert_response :success
end
The new behavior adds a simple SPAM trap field
that bots will usually fall for.
If a bot is submitting the email_confirmation field (which is hidden by a CSS
class), then it is SPAM and it gracefully ignores the request.
The test only tests the scenario where the bot is performing an AJAX
request. Then I thought that SPAM bots might try to submit a non-AJAX html
request.
So I wrote some more:
test "gracefully ignores spammy requests with valid attributes (AJAX)" do
@valid_contact = contacts(:two)
attributes = @valid_contact.attributes
attributes.merge!(email_confirmation: @valid_contact.email)
assert_no_difference("Contact.count") do
post :create, contact: attributes, format: 'js'
end
assert_response :success
end
test "gracefully ignores spammy requests with valid attributes (HTML)" do
@valid_contact = contacts(:two)
attributes = @valid_contact.attributes
attributes.merge!(email_confirmation: @valid_contact.email)
assert_no_difference("Contact.count") do
post :create, contact: attributes, format: 'html'
end
assert_response :success
end
Now that is ridiculous, why should I copy/paste this? There is only one
parameter (format) that varies between them.
Read more here!
Post a comment