Reputation: 219
Hello I am using rspec to test my user model. I just wanted to know if what I am doing is a common practice in testing. To test for error messages I am doing something like this
User.create!(users(:first))
user.update_attributes email: 'IDon\'tThinkThisIsAValidEmail'
user.should_not be_valid
assert user.errors.messages.include? :email
Also how would I go about testing for duplicates? Calling full_messages and testing for "Email has already been taken" message? Is this a good practice. I am doing tests this way because before my should_not be_valid tests were passing because the username was invalid so that was no good. IS what I am doing a good idea? Any better ways of testing?
Upvotes: 0
Views: 498
Reputation: 1355
For validating the format of an email you can do something like the following. Note that you don't have to create a user record or use fixtures for writing most validation specs.
it "will not allow invalid email addresses" do
user = User.new(email: 'notAValidEmail')
user.should have(1).error_on(:email)
end
it "will allow valid email addresses" do
user = User.new(email: '[email protected]')
user.should have(:no).errors_on(:email)
end
For validating presence you can do this:
it { should validate_presence_of(:email) }
You can see the rspec documentation for more examples:
https://www.relishapp.com/rspec/rspec-rails/v/2-3/docs/model-specs/errors-on
Upvotes: 1
Reputation: 19145
You should check out the shoulda gem, which has a suite of useful test assertions, including for uniqueness validations:
describe User do
should validate_uniqueness_of(:email)
end
Edit: Here's a link to the docs as a great place to start.
Upvotes: 2