Rails模型方法rspec测试

时间:2014-12-01 22:40:46

标签: ruby-on-rails testing rspec

我有以下测试:

它应该返回车库中的其他车辆阵列(不包括其自身)'do     g1 = FactoryGirl.create(:车库)

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])

应该在我的模型上测试这个方法:

  def other_cars_at_garage
    garage.cars.where.not(id: self.id)
  end

当我运行测试时,它会在返回时失败:#<ActiveRecord::AssociationRelation []>

我应该如何通过这项测试?如何检查AR :: AssociationRelation?

1 个答案:

答案 0 :(得分:0)

您没有保存c1 / c2 / c3和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

此外,最好使用

expect(c1.other_cars_at_garage).to match_array([c2, c3])

注意match_array而不是eq,这意味着数组的顺序并不重要,其中eq表示数组的顺序很重要