Question

I'm having trouble with the following attributes within my class. I have a date attribute with presence true that is enforced at database level too:

validates :date, presence: true

In addition to that, I need to enforce combined uniqueness for the following two attributes

validates :name, uniqueness: { scope: :parent_id }

So far... everything is ok, but I want to have a spec testing the uniqueness

it { should validate_uniqueness_of(:name).scoped_to(:parent_id) }

But the problem with line above is that it will try to insert a record on db by just using a random name and parent_id values letting the date one to be nil. Thus, it fails on database.

I already tried doing subject { build(:my_model) } on the test, however the it line is still creating it's own one and not setting the date attribute.

How can I make shoulda to use the subject I created? I am missing something?

Was it helpful?

Solution

Shoulda matchers needs to create a separate record in the database to test the case where it is not unique. It skips rails validations to do this, but cannot skip your database validations. If you create one manually, it'll use that instead. Change your test to this:

subject { FactoryGirl.build(:my_model) }
it { should validate_uniqueness_of(:name).scoped_to(:parent_id) }

This is covered in more depth in the shoulda matchers documentation. http://www.rubydoc.info/github/thoughtbot/shoulda-matchers/Shoulda/Matchers/ActiveRecord#validate_uniqueness_of-instance_method

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top