我有一个Ownership
模型,其中包含start_date
和end_date
。我在 app / models / ownership.rb 中定义了一个方法,如下所示:
def current?
self.start_date.present? && self.end_date.nil?
end
我在 spec / models / ownership_spec.rb
中测试此方法describe Ownership do
let(:product) { FactoryGirl.create(:product) }
let(:user) { FactoryGirl.create(:user) }
before { @ownership = user.ownerships.build(product: product) }
subject { @ownership }
describe "when owning and giving date are nil" do
before do
@ownership.save
@ownership.update_attributes(start_date: nil, end_date: nil, agreed: true)
end
it { should be_valid }
@ownership.current?.should be_false
describe "then product is owned" do
before { @ownership.update_attributes(start_date: 1.day.ago) }
it { should be_valid }
@ownership.current?.should be_true
end
end
end
end
但是rspec并不喜欢它并返回:
undefined method `current?' for nil:NilClass (NoMethodError)
你知道为什么@ownership
似乎对rspec没什么意义吗?
答案 0 :(得分:0)
您应该将所有断言/检查放到it
块。不要像这样放置裸体支票。
it { should be_valid }
@ownership.current?.should be_false # incorrect scope here
请改为:
it { should be_valid }
it { subject.current?.should be_false }
或者更好地做到这一点:
it { should be_valid }
its(:current?) { should be_false }