如何在控制器中获取一个模型?
示例:
# Model Spec
it 'does something' do
allow(model).to receive(:value).and_return 100
model2 = FactoryGirl.create :model
allow(model2).to receive(:value).and_return 99
# next line fails because it returns 100. when fetched, model2.value = 0
expect(model.subtract_last_model).to eq 1
end
# Model
def subtract_last_model
value - Model.last.value
end
我需要能够将model2
又名Model.last
存根以返回99。
当然,我可以编写以下内容,然后编写一个规范来查看是否使用正确的参数进行了调用,但如果有其他方法,我很好奇:
def subtract_model(model)
value - model.value
end
答案 0 :(得分:1)
Model.last
不返回存根model2
,但会从数据库重新加载未存档的model2
版本。因此:
it 'does something' do
allow(model).to receive(:value).and_return 100
model2 = FactoryGirl.create :model
allow(model2).to receive(:value).and_return 99
allow(Model).to receive(:last).and_return(model2)
expect(model.subtract_last_model).to eq 1
end
答案 1 :(得分:1)
它'简单,只需使用Model
存根model2
:
it 'does something' do
allow(model).to receive(:value).and_return 100
model2 = FactoryGirl.create :model
# stub Model
allow(Model).to receive(:last).and_return model2
allow(model2).to receive(:value).and_return 99
# next line fails because it returns 100. when fetched, model2.value = 0
expect(model.subtract_last_model).to eq 1
end