RSpec / FactoryGirl - Rails STI - Equality
Simplified example:
I recently installed Single Table Inheritance
in a model Animal
. Cat
and Dog
are subclasses Animal
.
I have a Animal
factory:
factory :animal do
type { ["Dog","Cat"] }.sample
end
Almost everywhere in my test suite, I call
let(:animal) { Factory.create(:animal) }
because the type Animal
is irrelevant to the test. Since I switched to STI, I get errors when I do equality checks on these animals, because the superclass is Animal
returned by a factory, but when the related objects are instantiated Animal
, they return the subclass.
Example:
expect(zoo.animal).to eq(animal)
fails:
expected: #<Cat:0x007fa01a8cd360 same_other_attributes...>
actual: #<Animal:0x007fa01b8d33b8 same_other_attributes...>
Is there a way to change the Animal
factory to return an instance of its subclass?
I tried to call .reload
in Animal
after the establishment of factory, but did not initiate the restart of a new (sub) class. I know you can usually call superclass.becomes!(subclass)
to force the change, but don't know how to put it in the callback FactoryGirl
in a way that will actually return the converted object.
source to share