Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stub Method error in request spec

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?

like image 530
Alex Avatar asked Oct 17 '14 15:10

Alex


2 Answers

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

like image 74
Nelson Patricio Jimenez Avatar answered Oct 10 '22 11:10

Nelson Patricio Jimenez


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!

like image 43
kurenn Avatar answered Oct 10 '22 11:10

kurenn