gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 06:59:37 24 4
gpt4 key购买 nike

我用 this book 学习了关于 RoR(Ruby-2.1,Rails 4.x)的 api 教程.

这是一本值得学习的好书,但我在第 5 章 的 rspec 测试中遇到了这个问题。 (请参阅该章中的 list 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,也许你可以用这个替换代码:

规范/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
end

app/controllers/concerns/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 stub Controller 辅助方法存在错误。更多引用 https://github.com/rspec/rspec-rails/issues/1076

关于ruby-on-rails - 请求规范中的 stub 方法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26428882/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com