【问题标题】:undefined method `response' for nil:NilClass rspec testnil:NilClass rspec 测试的未定义方法“响应”
【发布时间】:2015-02-28 20:22:42
【问题描述】:

我创建了一个测试,由于某种原因,应该在 nil 类型上运行。 我正在使用 rails 4.2 和 rspec-rails 3.1.0。我不确定我做错了什么 - 这是测试,错误出现在最后一个 it { should respond_with 401 } 测试

require 'rails_helper'

class Authentication
  include Authenticable
  def request
  end

  def response
  end
end

describe Authenticable do
  let(:authentication) { Authentication.new }

  describe "#current_user" do
    before do
      @user = FactoryGirl.create :user
      request.headers["Authorization"] = @user.auth_token
      allow(authentication).to receive(:request).and_return(request)
    end
    it "returns the user from the authorization header" do
      expect(authentication.current_user.auth_token).to eql @user.auth_token
    end
  end

  describe "#authenticate_with_token" do
    before do
      @user = FactoryGirl.create :user
      allow(authentication).to receive(:current_user).and_return(nil)
      allow(response).to receive(:response_code).and_return(401)
      allow(response).to receive(:body).and_return({"errors" => "Not authenticated"}.to_json)
      allow(authentication).to receive(:response).and_return(response)
    end

    it "render a json error message" do
      expect(json_response[:errors]).to eql "Not authenticated"
    end

    it {  should respond_with 401 }
  end
end

【问题讨论】:

  • 看起来allow(response) 中的response 在用于之前的块之前没有设置。该变量/方法名称指的是什么?
  • 我不明白authenticate_with_token 测试的意义何在,你伪造请求和响应,并期待虚假响应,你不应该至少做一个请求吗?
  • 我不太确定,我正在使用教程并且响应就在那里 - 我认为这是 rspec 的事情 - 因为我没有定义它。
  • 你有 infer_spec_type_from_file_location 吗!开启了吗?
  • 这就是 apionrails 教程上的人正在做的事情,不要问我有什么意义,我只知道它对他有用,但对我无效。问题是他使用的是 rails 4 和旧的 rspec 语法。

标签: ruby-on-rails ruby rspec


【解决方案1】:

it { should respond_with 401 } 没有指定哪个对象应该以 401 响应,这就是错误的原因。

尝试修复它:

expect(response).to respond_with 401

或 使用subject:

subject{ response }
it {  should respond_with 401 } 

【讨论】:

    【解决方案2】:
    subject { authentication }
    

    你应该把这行写成下面

    let(:authentication) { Authentication.new }
    subject { authentication }
    describe '#current_user' do
    

    【讨论】:

      猜你喜欢
      • 2013-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多