Michael Chaney
Michael Chaney

Reputation: 3041

Getting tripped up by verify_partial_doubles with rails 4 and rspec 3

I'm using authlogic for my user authentication and in my ApplicationController I have "current_user", "current_user_session", etc. defined and set as helper_methods.

I have an extremely simple view spec for my main index:

RSpec.describe "main/index.html.erb", :type => :view do
  context "when not logged in" do

    before do
      allow(view).to receive(:current_user).and_return(nil)
    end

    it "has an h1" do
      render
      expect(rendered).to include('h1')
    end

  end
end

The problem is that if "mocks.verify_partial_doubles = true" in my config then this causes an impressively massive error as it dumps an entire object and then says at the bottom:

  1) main/index.html.erb when not logged in has an h1
     Failure/Error: allow(view).to receive(:current_user).and_return(nil)
       #<#<Class:0x00000104c249d0>:.........
       @rendered_views={}>> does not implement: current_user

Of course, it is recommended that verify_partial_doubles is set to true, but in doing so this breaks. I pulled this straight from the documentation:

https://www.relishapp.com/rspec/rspec-rails/v/3-1/docs/view-specs/view-spec#passing-view-spec-that-stubs-a-helper-method

If the method appears in ApplicationHelper it'll work. But if it's in ApplicationController and defined as a helper_method there's no such luck:

helper_method :current_user, ...

def current_user
  return @current_user if defined?(@current_user)
  @current_user = current_user_session && current_user_session.record
end

I want the protection that verify_partial_doubles provides, how can I work around this?

Upvotes: 5

Views: 927

Answers (2)

romeu.hcf
romeu.hcf

Reputation: 73

You can disable double verification for views as follows:

RSpec.configure do |config|
  config.before(:each, type: :view) do
    config.mock_with :rspec do |mocks|
      mocks.verify_partial_doubles = false
    end
  end

  config.after(:each, type: :view) do
    config.mock_with :rspec do |mocks|
      mocks.verify_partial_doubles = true
    end
  end
end

This way you'll be able to keep stubbing view methods with:

allow(view).to receive(:current_user).and_return(nil)

More information at: https://github.com/rspec/rspec-rails/issues/1076

Upvotes: 0

namxam
namxam

Reputation: 96

This is a known issue and the only way to get it working is to extract the methods into a module and include it in your view helpers and the controller.

More information at: https://github.com/rspec/rspec-rails/issues/1076

Upvotes: 3

Related Questions