4
votes

I am trying to set local variable in view helper through rspec. My routine is as follow

def time_format(time)
    now = Time.now.in_time_zone(current_user.timezone)
end

My spec file is as follow:

it 'return 12 hour format' do
      user = User.first
      assign(:current_user, user)
      expect(helper.time_format(900)).to eq('9:00 AM')
end

Spec is failing throwing me error undefined local variable or method 'current_user'

'current_user' resided in application_controller

1

1 Answers

6
votes

Problem

Your current_user method is not available in your rspec test. That's why you are getting the mentioned error.

Solution

You either can implement current_user method inside a test helper and then use that in your test, or you can stub current_user in your spec test like this:

let(:user) { User.new }

# RSpec version >= 3 syntax:
before { allow(controller).to receive(:current_user) { user } }
before { allow(view).to receive(:current_user) { user } }

# RSpec version <= 2 syntax:
before { controller.stub(:current_user) { user } }
before { view.stub(:current_user) { user } }

This should fix your problem.

Also, if you are using devise for authentication, then I would recommend you to take a look at: How To: Test controllers with Rails 3 and 4 (and RSpec).