user2320239 user2320239 - 3 months ago 10
Ruby Question

Testing uniqueness validation

I'm trying to learn rspec and have ran into a problem, I'm trying to test the uniqueness validation on one of my models, but the test keeps failing even though I'm pretty sure it should pass.

Here is my test:

context "two products with the same title" do
Given{FactoryGirl.build(:product, title: "Hello test title")}
Given(:post2){FactoryGirl.build(:product, title: "Hello test title")}
Then{post2.invalid?}
end


and here is my validator:

validates :title, uniqueness: true


however when I run the test it comes back failed and I'm not sure why?

any help would be great!

Answer

You need to add uniqueness validation on title Validate uniqueness of an attribute

validates :title, uniqueness: true

And also you have to create first product not just build it

context "two products with the same title" do
  Given{FactoryGirl.create(:product, title: "Hello test title")}
  Given(:post2){FactoryGirl.build(:product, title: "Hello test title")}
  Then{post2.invalid?}
end

This will create one product with title = "Hello test title"

And for second product with same title product will be invalid