Skip to content

Instantly share code, notes, and snippets.

@jefflunt
Last active January 3, 2016 01:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jefflunt/8387633 to your computer and use it in GitHub Desktop.
Save jefflunt/8387633 to your computer and use it in GitHub Desktop.
Writing tests for AR validations
class Order < ActiveRecord::Base
...
validates :customer_id,
:company_id,
:credit_card_id,
:tip,
:delivery_location,
presence: true
...
end
class OrderTest < ActiveSupport::TestCase
...
[ :customer_id, :credit_card_id, :delivery_location, :company_id, :tip ].each do |field|
should validate_presence_of field
end
...
end
@jefflunt
Copy link
Author

The only thing this set of tests does is make sure that the validations don't get removed for the set of fields specified. These tests DO NOT make sure that the validations work - that's ActiveRecord's job. I've specified a correct validation, and I want to make sure that it stays in that class definition. I must trust ActiveRecord to take my correct validation and do the right thing, which is to return the correct value from the .valid? method.

@franckverrot
Copy link

IMHO if this is some sort of double check (like "am I really sure I should remove those validations because I would have to go modify the tests too") it's not something I would want to write.

I used to write lots of tests on AR, on the router, etc. None of these are actually worth the effort. What's worth the effort though is to isolate the app from the framework, and test the interactions. YMMV :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment