Draper Decorator spec not able to use Devise current_user method

1.3k Views Asked by At

I have a PostDecorator class in app/decorators/post_decorator.rb. It has a method that calls Devise's current_user method. It looks like this:

class PostDecorator < Draper::Decorator
  delegate_all

  def voter
    h.current_user
  end
end

I have a PostDecorator spec in spec/decorators/post_decorator_spec.rb

require 'spec_helper'

describe PostDecorator, type: :decorator do
  let(:post) { FactoryGirl.create(:post) }
  let(:user) { FactoryGirl.create(:user) }
  before { allow(helper).to receive(:current_user) { user } }

  describe 'voter' do
    it 'returns the current_user' do
      expect(post.voter).to eq user
    end
  end
end

When I run this I get an undefined method error:

<Draper::HelperProxy:0x007fb1c4f85890 ... does not implement: current_user

Gem Versions:

  • draper (1.4.0)
  • rspec-rails (3.4.1)
  • devise (3.5.5)

Also I should note everything in my app/lib directory is auto loaded. In application.rb I have config.autoload_paths << Rails.root.join('lib')

2

There are 2 best solutions below

2
On BEST ANSWER

The issue is related to Draper. Decorator is unable to access helper methods after sending an ActionMailer email.

This is an open issue on Draper's GitHub

To solve this I just modified the User Factory by adding a confirmed_at:

factory :user do
  ...
  confirmed_at DateTime.now
end

This way Devise won't send a Confirmation email.

0
On

Two things I think you need to do.

1.) Add devise test helpers to your decorator tests,

RSpec.configure do |config|
  config.include Devise::TestHelpers, type: :decorator
end

2.) you actually need to sign_in to expect post.voter to eq an actual users

require 'spec_helper'

describe PostDecorator, type: :decorator do
  let(:post) { FactoryGirl.create(:post) }
  let(:user) { FactoryGirl.create(:user) }
  before do
    sign_in user
  end

  describe '.voter' do
    it 'returns the current_user' do
      expect(post.voter).to eq user
    end
  end
end