在块之前的rspec范围的问题

时间:2014-11-25 06:32:56

标签: ruby rspec

我已经找到了答案,但我似乎无法弄清楚出了什么问题。我有一个api客户端测试,如下所示:

module MyTests
  describe '#update' do

    # using a before(:all) block for setup
    before(:all) do
      @client1 = Client.new
      @initial_payload_state = @client1.update.payload
    end

    context 'with a known starting payload' do
      # The payload is some nasty nested json so I grab an existing one
      # and then use a helper method to convert it to a full payload.
      # Then I update the client with the new payload. I'm using before(:each)
      # so I can get the client into this state for every test.
      before(:each) do
        @full_payload_state = helper_method(@initial_payload_state)
      end

      context 'alter_payload_1 works' do
        # now that I have the payload in its full state I'd like to alter it to
        # produce a certain output
        before(:all) do
          @new_payload_state = alter_payload_1(@full_payload_state)
        end

        # I now want to update the client with the altered payload and make sure
        # it has the same data. The request and response bodies are formatted slightly
        # differently in this case.
        it 'works' do
          @updated_payload_state = @client1.update(@new_payload_state)
          expect(payloads_equal?(@full_payload_state, @new_payload_state).to eq true
        end
      end

      context 'alter_payload_2 works' do
        before(:all) do
          @new_payload_state = alter_payload_2(@full_payload_state)
        end

        it 'works' do
          @updated_payload_state = @client1.update(@new_payload_state)
          expect(payloads_equal?(@full_payload_state, @new_payload_state).to eq true
        end
      end

实际上,我之前设置的块要长得多,所以我认为保持这种方式是有意义的。我尝试使用before(:each)块,因此我可以使用相同的已知状态来启动每个alter_payload上下文。问题是,使用此设置,我得到此行的无方法错误:

@new_payload_state = alter_payload_1(@full_payload_state)

建议@full_payload_state为零。我确定我在范围方面有问题,但我不确定为什么或如何解决它。任何帮助非常感谢!

1 个答案:

答案 0 :(得分:1)

看起来像before(:all)的范围问题。

一般来说,在(:all)之前停止使用是明智的,因为它会妨碍你的测试。

将before(:all)行替换为before(:each),这将使您的每个测试独立于其他测试。这可能会帮助您找到故障。