accessing current_user in helper

1,437 views
Skip to first unread message

David Moulton

unread,
Apr 3, 2012, 3:04:09 PM4/3/12
to ur...@googlegroups.com
I'm trying to rspec test a helper in a rails 3.1 app that is using devise. The helper uses devise's current_user. My test looks like this:

require 'spec_helper'

describe ApplicationHelper do
 before :each do
  user = User.new(:email=>'us...@example.com')
  helper.stub!(:current_user).and_return(user)
 end

 it "should have no menus" do
   get_main_menu_items.should be_empty
 end
end



Running that results in this error:


undefined local variable or method `current_user' for #<RSpec::Core::ExampleGroup::Nested_1:0x007f7fdac46678>


I'm sure I'm missing something, but not sure what it is. Anyone have any ideas?

dave

Eric Berry

unread,
Apr 3, 2012, 3:08:49 PM4/3/12
to ur...@googlegroups.com
you have helper.stub. Shouldn't it be user.stub?

--
Utah Ruby Users Group
ur...@googlegroups.com
http://utruby.org
http://bit.ly/urug_lunches
http://groups.google.com/group/urug/
- All meeting times and places can be found here.
 
** Please prefix your subject with "[JOB]" if your message is about job opportunities.

Justin Shakespear

unread,
Apr 3, 2012, 3:16:39 PM4/3/12
to ur...@googlegroups.com
Are you including the devise test helpers?

spec_helper.rb:
RSpec.configure do |config|
  config.include Devise::TestHelpers, :type => :controller
end


On Tue, Apr 3, 2012 at 1:04 PM, David Moulton <da...@themoultons.net> wrote:

--

David Moulton

unread,
Apr 3, 2012, 3:24:43 PM4/3/12
to ur...@googlegroups.com
I do have the config line in place.

Using user.stub has the same result. I've also tried controller.stub, but I assume a helper test has to reference to a controller.

-- 
David Moulton
Sent with Sparrow

Justin Shakespear

unread,
Apr 3, 2012, 3:28:11 PM4/3/12
to ur...@googlegroups.com
You can specify. The example I posted just happens to reference controllers.

Trey Bean

unread,
Apr 3, 2012, 3:38:29 PM4/3/12
to ur...@googlegroups.com
You need to call call your helper on the rspec helper object, e.g.

it "should have no menus" do
  helper.get_main_menu_items.should be_empty
end

Hope that helps,
Trey

David Moulton

unread,
Apr 3, 2012, 3:41:30 PM4/3/12
to ur...@googlegroups.com
Trey, I think that did it. Thanks to everyone for the help.

-- 
David Moulton
Sent with Sparrow

Justin Shakespear

unread,
Apr 3, 2012, 3:44:22 PM4/3/12
to ur...@googlegroups.com
THREE CHEERS FOR TREY!!!

Trey Bean

unread,
Apr 3, 2012, 3:52:09 PM4/3/12
to ur...@googlegroups.com
I'd prefer 3 beers, but given it was just a little rspec experience, I'll deal with the cheers. :)

Glad that helped, David.

Ramana A

unread,
Jul 11, 2013, 9:59:05 AM7/11/13
to ur...@googlegroups.com
Thanks Trey, it helped me.
Reply all
Reply to author
Forward
0 new messages