2015-10-18 8 views
3

Я попытался следующие:Какова область действия 'let' в Rspec?

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 для let и для создания экземпляров в Rspec.

Какой здесь вариант использования let здесь, а только для меня, используя schedule = blah blah?

Я думаю, я понимаю буквального намерение ошибки: Я не могу использовать schedule в context только в it. Но что это правильный путь, то этот пример, чтобы положить вещи под описания, контекст, или это и каким образом?

ответ

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' в переднем блоке. Он находится в описываемом блоке или вложенном блоке описания за пределами примера. Код в блоках 'before' выполняется в том же контексте, что и в примере. – zetetic