user2320239
user2320239

Reputation: 1038

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!

Upvotes: 1

Views: 1248

Answers (2)

Deepak Mahakale
Deepak Mahakale

Reputation: 23661

You need to add uniqueness validation on title:

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

Upvotes: 2

hcarreras
hcarreras

Reputation: 4612

You should use a gem like shoulda-matchers for testing this kind of tests: https://github.com/thoughtbot/shoulda-matchers It will save you a lot of time and it will DRY your tests (since they are all the same)

Regarding your test, I'm not sure what are you trying to achieve. You are not validating uniqueness there, only length of the product. For adding the uniqueness you add to your Product model:

validates :title, uniqueness: true

And when making the tests, you should create (instead of build) your first Product. Basically, unless your Product is stored in the database, your products will be valid because it doesn't exists (yet) any other Product like that one.

Upvotes: 0

Related Questions