A Rails 7.0 migration includes the attribute t.bigint :status_id, default: 6
Which is invoked in the model as
belongs_to :status, class_name: 'Categoryminor'
If a test is run
shop = Shop.new(name: 'apatride')
assert shop.valid?
the Unit test will complain #<ActiveModel::Errors [#<ActiveModel::Error attribute=status, type=blank, options={:message=>:required}>]>
notwithstanding the schema clearly states t.bigint "status_id", default: 6
and verifying with postgresql, that default value is well defined there.
Changing the class
belongs_to :status, class_name: 'Categoryminor', optional: true
allows the test to pass, but this is somewhat non-sensical. If there is a default value, the attribute cannot be blank.
What is the reasoning going on here?
CodePudding user response:
belongs_to
relations have presence validation since rails 5. Putting a random status_id is not enough. There must be a record in CategoryMinor
table with the id of 6, and in the case of tests, the fixture has to be properly invoked.
Two material ways to resolve this:
- add an id value to the fixture
status: id: 6
- write the test to call the fixture object without the id ` The latter is not pithier, but less prone to further complications.