未定义的方法`响应'为零:NilClass rspec测试

时间:2015-02-28 20:22:43

标签: ruby-on-rails ruby rspec

我创建了一个测试,由于某种原因,应该在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

2 个答案:

答案 0 :(得分:2)

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

要修复它,请尝试:

expect(response).to respond_with 401

或 使用subject

subject{ response }
it {  should respond_with 401 } 

答案 1 :(得分:2)

subject { authentication }

你应该把这一行放在下面

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