首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >请求规范中的存根方法错误

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

Stack Overflow用户
提问于 2014-10-17 15:55:40
回答 5查看 1.1K关注 0票数 7

我使用RoR(Ruby-2.1,Rails 4.x)学习这本书上的api教程。

这是一本很好的书,但我在第5章中的rspec测试中发现了这个问题。(请参见该章中的清单5.9 )。

代码语言:javascript
复制
Failure/Error: authentication.stub<:request>.and_return<request>
#<Authentication:0x000000075fe220> does not implement: request

源代码:

代码语言:javascript
复制
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

如何解决这个问题?

EN

回答 5

Stack Overflow用户

发布于 2014-12-08 20:46:05

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

spec/controllers/concerns/authenticable_spec.rb

代码语言:javascript
复制
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

app/控制器/关注点/身份验证.app

代码语言:javascript
复制
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存根控制器助手方法存在一个bug。更多参考资料https://github.com/rspec/rspec-rails/issues/1076

票数 5
EN

Stack Overflow用户

发布于 2014-12-08 17:54:41

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

代码语言:javascript
复制
group :test do
 gem "rspec-rails", "~> 2.14"
end

告诉我是怎么回事!

票数 1
EN

Stack Overflow用户

发布于 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进行测试的样子。

代码语言:javascript
复制
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

希望这能有所帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26428882

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档