我使用RoR(Ruby-2.1,Rails 4.x)学习这本书上的api教程。
这是一本很好的书,但我在第5章中的rspec测试中发现了这个问题。(请参见该章中的清单5.9 )。
Failure/Error: authentication.stub<:request>.and_return<request>
#<Authentication:0x000000075fe220> does not implement: request源代码:
class Authentication
include Authenticable
end
describe Authenticable do
let(:authentication) { Authentication.new }
describe "#current_user" do
before do
@customer = FactoryGirl.create :customer
request.headers["Authorization"] = @customer.auth_token
authentication.stub(:request).and_return(request)
end
it "returns the user from the authorization header" do
expect(authentication.current_user.auth_token).to eql @customer.auth_token
end
end
end如何解决这个问题?
发布于 2014-12-08 20:46:05
如果您想使用rspec 3,也许可以用以下代码替换代码:
spec/controllers/concerns/authenticable_spec.rb
require 'rails_helper'
class Authentication
include Authenticable
end
describe Authenticable, :type => :controller 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
endapp/控制器/关注点/身份验证.app
module Authenticable
# Devise methods overwrites
def current_user
@current_user ||= User.find_by(auth_token: request.headers['Authorization'])
end
def request
request
end
endpdt:使用rspec存根控制器助手方法存在一个bug。更多参考资料https://github.com/rspec/rspec-rails/issues/1076
发布于 2014-12-08 17:54:41
我是这本书的作者,您使用的是哪个版本的RSpec?,您可能需要将其设置为2.14,如下所示:
group :test do
gem "rspec-rails", "~> 2.14"
end告诉我是怎么回事!
发布于 2015-01-08 11:26:57
我会尝试按照建议用“rspec”、"~> 2.14“来完成这个项目。
一旦完成了本教程,您就可以使用transpec --一个gem,它将升级您的测试,使其与rspec3兼容。
https://github.com/yujinakayama/transpec
安装gem并将您的项目>gem文件升级到“rails”、"~> 3.1.0“,并在项目上运行transpec。
这将更新您的所有测试。
我认为这就是使用rspec 3进行测试的样子。
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希望这能有所帮助。
https://stackoverflow.com/questions/26428882
复制相似问题