nil:NilClass rspec 测试的未定义方法“响应”
undefined method `response' for nil:NilClass rspec test
我创建了一个测试,出于某种原因,应该 运行 为 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
it { should respond_with 401 }
没有指定哪个对象应该用 401 响应,这就是错误的原因。
要修复它,请尝试:
expect(response).to respond_with 401
或
使用 subject:
subject{ response }
it { should respond_with 401 }
subject { authentication }
你应该把这行写成下面的样子
let(:authentication) { Authentication.new }
subject { authentication }
describe '#current_user' do
我创建了一个测试,出于某种原因,应该 运行 为 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
it { should respond_with 401 }
没有指定哪个对象应该用 401 响应,这就是错误的原因。
要修复它,请尝试:
expect(response).to respond_with 401
或 使用 subject:
subject{ response }
it { should respond_with 401 }
subject { authentication }
你应该把这行写成下面的样子
let(:authentication) { Authentication.new }
subject { authentication }
describe '#current_user' do