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

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 请求规范中的Stub方法错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我用 this book研究了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

怎么解决这个问题?

解决方法

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

规格/控制器/关切/ 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
end

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

module Authenticable
  # Devise methods overwrites
  def current_user
    @current_user ||= User.find_by(auth_token: request.headers['Authorization'])
  end

  def request
    request
  end
end

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

猜你在找的Ruby相关文章