2015-10-18 81 views
3

我试过如下: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 

我周围范围的错误:

`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) 

不仅为这个例子,但是其他时间,我不完全明白什么是允许的scope是让和在Rspec中创建实例。

let这里的用例与我只用schedule = blah blah创建的用例有什么区别?

我想我明白字面意图的错误:我不仅可以在it.使用contextschedule但是,什么是正确的做法,然后用这个例子来把东西下介绍,背景,或者用什么方式?

回答

4

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

从文档:

Use let to define a memoized helper method. The value will be cached across multiple calls in the same example but not across examples.

Note that let is lazy-evaluated: it is not evaluated until the first time the method it defines is invoked. You can use let! to force the method's invocation before each example.

By default, let is threadsafe, but you can configure it not to be by disabling config.threadsafe, which makes let perform a bit faster.

你得到丢失,因为这条线的位置的方法:

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

似乎要在每个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 
+0

谢谢。我觉得这很有道理。所以我可以在上下文中使用let块吗?我不仅限于'它'块。 – Angela

+0

只应该用于描述层面吗? – Angela

+0

您不能在块前使用'let'。它位于示例之外的描述块或嵌套描述块中。 ''之前'块中的代码在与示例相同的上下文中运行。 – zetetic