0

我有一个Ownership带有 astart_date和 a的模型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 似乎为零吗?

4

1 回答 1

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 }
于 2013-07-23T10:08:53.123 回答