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?
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. https://www.rubydoc.info/gems/shoulda-matchers/Shoulda%2FMatchers%2FActiveRecord:validate_uniqueness_of