Reputation: 193
I am new to rails and I'm trying to understand testing using Rspec. I created a simple model (just for testing purposes) named Contact that contains firstname:string, lastname:string and email:string. I am just trying to set a test for firstname to fail if is empty.
my Rspec test is as follow:
describe Contact do
it "creates a valid model" do
contact = Contact.new(
firstname: 'firstname',
lastname: 'lastname',
email: 'email'
)
expect(contact).to be_valid
end
it "is invalid without a firstname" do
contact = Contact.new(firstname: nil)
contact.valid?
expect(contact.errors[:firstname]).to include("can't be blank")
end
My understanding is that this test should not return any failures but it does. Output below:
Failures:
1) Contact is invalid without a firstname
Failure/Error: expect(contact.errors[:firstname]).to include("can't be blank")
expected [] to include "can't be blank"
# ./spec/models/contact_spec.rb:16:in `block (2 levels) in <top (required)>'
Finished in 0.11659 seconds (files took 2.39 seconds to load)
18 examples, 1 failure, 15 pending
Failed examples:
rspec ./spec/models/contact_spec.rb:13 # Contact is invalid without a firstname
If I change the expect statement from ".to" to "not_to" the test passes, so I think I am getting this backwards, any help or explanation is greatly appreciated.
Upvotes: 0
Views: 1027
Reputation: 193
As smathy said in the comments, I forgot to include the validation inside my model. That solved my problem.
Upvotes: 1