Rspec: let 不起作用

Rspec: let does not work

我有一些 Rspec 测试,我用 let:

初始化变量
  describe 'methods' do

    let(:order)   { Order.new }
    let(:event_1) { FactoryGirl.create(:event) }
    let(:event_2) { FactoryGirl.create(:event) }

    context 'should checks if any event is paid' do
      order.events << event_1
      order.events << event_2
      order.events_paid?.should == true
    end

    context 'should write aasm state' do
      order.aasm_write_state('new')
      order.state.CanonicalName.should == 'new'
    end

  end

但是我得到一个错误'method_missing': 'order' is not available on an example group (e.g. a 'describe' or 'context' block). It is only available from within individual examples (e.g. 'it' blocks) or from constructs that run in the scope of an example (e.g. 'before', 'le', etc). (RSpec::Core::ExampleGroup::WrongScopeError)

为什么 let 初始化不起作用?

我看到两个错误:

  • 您还没有将测试包装在 it 块中 (!)

  • 您尝试将事件与 order 相关联,但 order 未保留


旁注,现在约定使用以下语法:

expect(order.events_paid?).to be true

TL;DR:将 context 更改为 it 即可。


这里的问题是context定义了一个示例组,而不是一个示例。示例组和示例根本不同;一个示例组是一个 class,用于将具有通用设置代码的示例分组,并且一个示例作为该 class 的实例运行。当您使用 let 时,您定义的方法可从同一示例组中定义的示例访问。 it是定义实例的主要方法

有关详细信息,请参阅 rspec 核心自述文件中的 note on scope

附带说明一下,我写了错误消息,您将尝试解释这一点,但显然它没有达到那个目的。您对错误消息感到困惑的是什么?我们怎样才能让它变得更好,以免其他用户被这个绊倒?