mojo jojo
mojo jojo

Reputation: 41

Set local variable rspec helper

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

Upvotes: 4

Views: 5556

Answers (2)

Mike Slinn
Mike Slinn

Reputation: 8403

The following was modified from the RSpec-core 3.10 docs.

Create a new setting for RSpec.configure called my_variable, and give it a value, like this:

# spec/spec_helper.rb

RSpec.configure do |config|
  config.add_setting :my_variable
  config.my_variable = "Value of my_variable"
end

Access settings like class variables in RSpec.configuration from your test:

# spec/my_spec.rb

RSpec.describe(MyModule) do
  it "creates an instance of something" do
    my_instance = MyModule::MyClass.new(RSpec.configuration.my_variable)
  end
end

Upvotes: 0

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34338

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).

Upvotes: 6

Related Questions