新手:使用构建或保存模型测试很困难

时间:2013-07-23 08:27:51

标签: ruby-on-rails rspec

我有一个Ownership模型,其中包含start_dateend_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没什么意义吗?

1 个答案:

答案 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 }