【问题标题】:Receiving undefined method error in Rspec PUT Call在 Rspec PUT 调用中接收到未定义的方法错误
【发布时间】:2012-10-23 15:01:27
【问题描述】:

在我的规范中,当我运行下面的 POST 请求时,一切正常。

    before do
      request_payload = {
        player: {
          first_name: "Joe",
          last_name: "Carradine",
          team_id: "1"
        }
      }

      post :create, request_payload
    end

但是当我运行 PUT 规范时:

    before do
      request_payload = {
        player: {
          first_name: "Buck",
          last_name: "Carradine",
          team_id: "1"
        }
      }

      put :update, { id: 3 }, request_payload
    end

我收到这样的错误:

 Failure/Error: put :update, { id: 1 }, request_payload
 NoMethodError:
   undefined method `[]' for nil:NilClass

我不知道什么被认为是 nil。此 API 调用在 REST 客户端中运行良好。

这是基于上一个 SO 问题的另一个错误:Receiving error in RSpec for PUT, but not POST

【问题讨论】:

  • 如果你这样做:put :update, { id: 3 }.merge(request_payload)
  • 这行得通(谢谢,您可以添加作为答案吗?),但是鉴于 id 哈希表示来自 URL 而不是来自有效负载的值,这种技术是一个很好的测试吗?
  • 实际上,通过表单传递的每一个数据都可以通过参数获得,所以你不会在那里作弊。

标签: ruby-on-rails api rest rspec tdd


【解决方案1】:

你应该这样做:

put :update, { id: 3 }.merge(request_payload)

【讨论】:

    【解决方案2】:

    我正在这样做:

    describe 'PUT #update' do
    
    before do
    
      @todo = FactoryGirl.create(:todo)
    
      @initial_title = @todo.title
      @initial_updated_at = @todo.updated_at
      @new_title = 'Title Changed'
    
      request_payload = { :title => @new_title }
    
      put :update, :id => @todo.id, :todo => request_payload, :format => :json
    
      @todo.reload
    
    end
    
    it 'should retrieve status code of 204' do
      response.status.should eq(204)
    end
    
    it 'updated attributes should not be as initially' do
      @todo.title.should_not eq(@initial_title)
      @todo.updated_at.should_not eq(@initial_updated_at)
    end
    
    it 'updated attribute should be the the same' do
      @todo.title.should eq(@new_title)
    end
    
    it 'updated date should be increased' do
      @todo.updated_at.should > @initial_updated_at
    end
    
    
    end
    

    可能对某人另外有用,进行类似测试的方式;)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多