Reputation: 7210
I have the following test:
it 'should return array of other cars at garage (excluding itself)' do g1 = FactoryGirl.create(:garage)
c1 = FactoryGirl.create(:car)
c1.garage = g1
c2 = FactoryGirl.create(:car)
c2.name = "Ford 1"
c2.garage = g1
c3 = FactoryGirl.create(:car)
c3.name = "VW 1"
c3.garage = g1
expect(c1.other_cars_at_garage).to eq([c2, c3])
end
which should test this method on my model:
def other_cars_at_garage
garage.cars.where.not(id: self.id)
end
When I run the test, it fails as it returns: #<ActiveRecord::AssociationRelation []>
How should I get this test to pass? How do I check for an AR::AssociationRelation?
Upvotes: 0
Views: 270
Reputation: 8826
You are not saving the association between c1/c2/c3 and g1
c1 = FactoryGirl.create(:car)
c1.garage = g1
c1.save #this saves g1 in c1's garage
c2 = FactoryGirl.create(:car)
c2.name = "Ford 1"
c2.garage = g1
c2.save
c3 = FactoryGirl.create(:car)
c3.name = "VW 1"
c3.garage = g1
c3.save
In addition, it's probably best to use
expect(c1.other_cars_at_garage).to match_array([c2, c3])
Notice the match_array
instead of eq
, this means the order of the array is unimportant, where as eq means the order of the array is important
Upvotes: 0