Home > database >  Rails Minitest for polymorphism
Rails Minitest for polymorphism

Time:07-04

A class was generated with associable:references{polymorphic}
Thus the schema has:

    t.string "associable_type", null: false
    t.bigint "associable_id", null: false

The fixtures auto-generated by rails have:

  associable: one
  associable_type: Associable

There was an attempt to modify the fixtures to reflect the schema:

  associable_id: 4
  associable_type: Chain

The following test

  test "valid " do
    contact = Contact.new(associable_id: 2, associable_type: 'User')
puts contact.valid?
puts contact.errors.inspect
    assert contact.valid?
  end

returns

false
#<ActiveModel::Errors [#<ActiveModel::Error attribute=associable, type=blank, options={:message=>:required}>]>

Changing the test to contact = Contact.new(associable: two, associable_type: 'User') complains with NameError: undefined local variable or method 'two' as per the autogenerated syntax

How can polymorphic records be properly tested?

CodePudding user response:

Fixtures are data which are created and that you can test against. We can refer https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html for detail understanding. In our case we don't need to modify the fixtures.

The error which we are getting in our test case is because we haven't created record in users table. So when it tries to validate the record it check whether the record with mentioned id associable_id: 2 (i.e 2 in our case) is present in users table or not.

You can modify test case as below

test "valid " do
  user = User.new(name: 'Jerome', email: '[email protected]')
  user.save
  Contact.new(associable: user)
  puts contact.valid?
  puts contact.errors.inspect
  assert contact.valid?
end

Note: I haven't add other columns as i am not aware of your users and contacts schema. Please add columns if there are any.

  • Related