我想为完美工作的模型编写一个测试 - 但由于某种原因测试没有返回预期的结果。工厂是否会自动在模型中运行方法?
我的模型包含此:
after_validation :set_conference
def rand_conference
r = rand.to_s[2..8]
while conference == r
r = rand.to_s[2..8]
end
r
end
def set_conference
self.conference = rand_conference unless conference.presence
end
end
而在我的模型试验我测试这个(理想情况下,我将测试如果“会议”是一个6位数字,但现在只是一个“不是零”就足够了):
厂:
FactoryGirl.define do
factory :plan do
name "Test"
description "Lorem Ipsum"
category "template"
end
end
Model_spec:
before (:each) do
@plan = build(:plan)
end
it "has a conference number" do
expect(@plan.conference).not_to be_empty
end
结果我得到:
1) Plan has a conference number
Failure/Error: expect(@plan.conference).not_to be_empty
NoMethodError:
undefined method `empty?' for nil:NilClass
是否factorygirl使用after_validation回调?
问题解决了,这就实现了。加分结构非常好的解释!更进一步,还有@fivedigit的答案,它也适用。 –
很高兴能帮到:) –