请求规范中的存根方法错误

时间:2014-10-17 15:55:41

标签: ruby-on-rails ruby rspec

我用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

如何解决此问题?

5 个答案:

答案 0 :(得分:5)

如果您想使用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

答案 1 :(得分:1)

我是这本书的作者,您正在使用哪个版本的RSpec?可能您必须将其设置为2.14,如下所示:

group :test do
 gem "rspec-rails", "~> 2.14"
end

让我知道它是怎么回事!

答案 2 :(得分:0)

我会尝试使用&#34; rspec-rails&#34;,&#34;〜&gt;完成项目。 2.14&#34;如建议的那样。

完成本教程后,您就可以使用transpec - 一个将您的测试升级为与rspec3兼容的gem。

https://github.com/yujinakayama/transpec

安装gem并升级您的项目&gt; gemfile to&#34; rspec-rails&#34;,&#34;〜&gt; 3.1.0&#34;并在项目上运行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

希望这会有所帮助。

答案 3 :(得分:0)

只需通过这种方式完成规范中的<%= f.input :my_date, as: :date_time_picker, input_html: { value: @my_entity.my_date.to_time.strftime("%d/%m/%Y") %> 课程:

Authentication

答案 4 :(得分:0)

我发现使用这个github issue#4我只需更改就能解决这个问题:

class Authentication

authenticable_spec.rb文件中:

class Authentication  < ActionController::Base

这意味着Authentication类继承了ActionController::Base请求方法。