2013-07-23 27 views
0

我有一個Ownership模型與start_dateend_date。我在應用程序/模型/ ownership.rb定義的方法,像這樣:新手:模型測試與建立或保存難

def current? 
    self.start_date.present? && self.end_date.nil? 
end 

我測試的規格/型號/ 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

你應該把所有斷言/檢查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 } 
+0

感謝您的快速,高效的答案! –