Reputation: 215
i am trying to write some views specs for my rails app, but i stumble on this error:
ActionView::Template::Error:
undefined local variable or method `current_user' for #<#<Class:0x007fa47d2612d0>:0x007fa47e267710>
Here is how i wrote my view spec :
describe "/newsletters/index.html.erb" do
include NewslettersHelper
include Authlogic::TestCase
def current_user(stubs = {})
@current_user ||= mock_model(User, stubs)
end
def user_session(stubs = {}, user_stubs = {})
@current_user_session ||= mock_model(UserSession, {:user => current_user(user_stubs)}.merge(stubs))
end
def login(session_stubs = {}, user_stubs = {})
UserSession.stub!(:find).and_return(user_session(session_stubs, user_stubs))
end
def logout
@user_session = nil
end
context "without a logged-in user" do
before(:each) do
activate_authlogic
logout()
assigns[:newsletters] = @newsletters = [ mock_model(Newsletter, :titre => "value for titre",
:sommaire => "value for sommaire", :content => "value for content") ]
end
it "renders a list of newsletters" do
# pending("find how to mock authlogic current user in views spec")
render
rendered.should have_selector("tr>td") do |row|
row.should have_content("value for titre")
end
rendered.should have_selector("tr>td") do |row|
row.should have_content("value for sommaire")
end
rendered.should have_selector("tr>td") do |row|
row.should have_content("value for content")
end
end
end
Upvotes: 1
Views: 805
Reputation: 12540
None of the answers worked for me (using rspec 3.9 here), as I was getting errors like #<#<Class:0x007fb9ca387dc8> does not implement: current_user
, trying to stub the view or controller objects, so I had to do it like:
before do
controller.singleton_class.class_eval do
# Just defining methods to being stubbed later
def current_user; end
def current_account; end
helper_method :current_user, :current_account
end
allow(controller).to receive(:current_user).and_return(user)
allow(controller).to receive(:current_account).and_return(account)
end
not the prettiest solution, but it worked.
Upvotes: 0
Reputation: 56
The view spec is an isolated context so you need to stub the current_user method in the view context.
view.stub(:current_user).and_return(mock_model(User))
For further reading on the view spec I suggest you the view spec page on relish
Upvotes: 1
Reputation: 1373
Try controller.stub(:current_user) { mock_model(User) }
I think it should help
Upvotes: 1