I study api tutorial on RoR(Ruby-2.1, Rails 4.x) with this book.
It is an excellent book to follow, but I got this issue in rspec test in Chapter 5. (Please see Listing 5.9 in that chapter.)
Failure/Error: authentication.stub<:request>.and_return<request>
#<Authentication:0x000000075fe220> does not implement: request
Source code:
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
How can fix this issue?
If you would like to use rspec 3, maybe you can replace the code with this:
spec/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: Exist a bug with rspec stub controller helper method. more references https://github.com/rspec/rspec-rails/issues/1076
I'm the author of the book, which version of RSpec are you using?, probably you will have to set it to 2.14 like so:
group :test do
gem "rspec-rails", "~> 2.14"
end
Let me know how it goes!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With