Rspec中'let'的范围是什么?

Tim*_* T. 5 ruby rspec let

我尝试了以下方法:

  describe "#check_recurring_and_send_message" do

    let(:schedule) {ScheduleKaya.new('test-client-id')}

    context "when it is 11AM and recurring event time is 10AM" do

      schedule.create_recurring_event('test-keyword', 'slack', 'day', '10 AM') 

      it "sends an SMS" do

      end

      it "set the next_occurrence to be for 10AM tomorrow" do 
        tomorrow = Chronic.parse("tomorrow at 10AM")
        expect(schedule.next_occurrence).to eq(tomorrow)
      end

    end

  end
Run Code Online (Sandbox Code Playgroud)

我在范围内遇到错误:

`method_missing': `schedule` 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`, `let`, etc). (RSpec::Core::ExampleGroup::WrongScopeError)
Run Code Online (Sandbox Code Playgroud)

不仅仅是这个例子,有时候,我还不完全理解scopelet和在Rspec中创建实例的允许内容.

这里的用例let与我创建的用例有什么关系schedule = blah blah

我想我明白了字面上的错误的意图:我不能使用schedulecontextit. 但是,什么是正确的做法,然后用这个例子来把东西下描述,背景,或者用什么方式?

Ant*_*ony 5

Let 懒惰评估,当你想跨测试共享一个变量时,这是很好的,但只有当测试需要它时.

来自文档:

使用let来定义memoized帮助器方法.该值将在同一示例中的多个调用之间缓存,但不跨示例缓存.

请注意,let是惰性求值的:直到第一次调用它定义的方法时才会对它进行求值.你可以用let!在每个示例之前强制执行方法的调用.

默认情况下,let是线程安全的,但您可以通过禁用config.threadsafe来配置它,这使得执行速度更快一些.

由于这条线,你在这里找不到一个方法:

schedule.create_recurring_event('test-keyword', 'slack', 'day', '10 AM') 
Run Code Online (Sandbox Code Playgroud)

您似乎希望在每个it块之前评估该行context.你只需要像这样重写它:

describe "#check_recurring_and_send_message" do
  let(:schedule) {ScheduleKaya.new('test-client-id')}
  context "when it is 11AM and recurring event time is 10AM" do
    before(:each) do
      schedule.create_recurring_event('test-keyword', 'slack', 'day', '10 AM')
    end
    it "sends an SMS" do
    end
    it "set the next_occurrence to be for 10AM tomorrow" do
      tomorrow = Chronic.parse("tomorrow at 10AM")
      expect(schedule.next_occurrence).to eq(tomorrow)
    end
  end
end
Run Code Online (Sandbox Code Playgroud)