ruby-on-rails – 请求规范中的Stub方法错误

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 请求规范中的Stub方法错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我用 this book研究了RoR(Ruby-2.1,Rails 4.x)的api教程.

这是一本很好的书,但我在第5章的rspec测试中得到了这个问题.(请参阅该章的清单5.9.)

  1. Failure/Error: authentication.stub<:request>.and_return<request>
  2. #<Authentication:0x000000075fe220> does not implement: request

代码

  1. class Authentication
  2. include Authenticable
  3. end
  4.  
  5. describe Authenticable do
  6. let(:authentication) { Authentication.new }
  7.  
  8. describe "#current_user" do
  9. before do
  10. @customer = FactoryGirl.create :customer
  11. request.headers["Authorization"] = @customer.auth_token
  12. authentication.stub(:request).and_return(request)
  13. end
  14. it "returns the user from the authorization header" do
  15. expect(authentication.current_user.auth_token).to eql @customer.auth_token
  16. end
  17. end
  18. end

怎么解决这个问题?

解决方法

如果您想使用rspec 3,也许您可​​以用以下代码替换代码

规格/控制器/关切/ authenticable_spec.rb

  1. require 'rails_helper'
  2.  
  3. class Authentication
  4. include Authenticable
  5. end
  6.  
  7. describe Authenticable,:type => :controller do
  8. let(:authentication) { Authentication.new }
  9.  
  10. describe "#current_user" do
  11. before do
  12. @user = FactoryGirl.create :user
  13. request.headers["Authorization"] = @user.auth_token
  14. allow(authentication).to receive(:request).and_return(request)
  15. end
  16.  
  17. it "returns the user from the authorization header" do
  18. expect(authentication.current_user.auth_token).to eql @user.auth_token
  19. end
  20. end
  21. end

应用程序/控制器/关切/ authenticable.rb

  1. module Authenticable
  2. # Devise methods overwrites
  3. def current_user
  4. @current_user ||= User.find_by(auth_token: request.headers['Authorization'])
  5. end
  6.  
  7. def request
  8. request
  9. end
  10. end

pdt:存在rspec存根控制器帮助方法错误.更多参考文献https://github.com/rspec/rspec-rails/issues/1076

猜你在找的Ruby相关文章