2014-11-25 51 views
1

我已經搜索了一個答案,但我似乎無法弄清楚發生了什麼問題。我有一個API客戶端測試,看起來像下面這樣:在之前的塊中rspec範圍的問題

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

看起來像以前(:所有)的範圍問題。

一般來說,明智地停止使用之前(:所有),因爲它糾纏你的測試。

用before(:each)替換之前的(:all)行,這會使每個測試獨立於其他測試。這可能會幫助你找到你的故障。