Marcin Doliwa
Marcin Doliwa

Reputation: 3659

Views testing and Devise's current_user

It's my first views test. Not sure if I understand whole mocks/stubs/doubles concept, so probably problem is there.

I'm testing simple Login/Signup | username/Logout links.

application.html.erb:

  ...
    <ul>
      <% if user_signed_in? %>
        <li>
          <%= link_to('Logout', destroy_user_session_path, :method => :delete) %>        
          <%= current_user.username %>
        </li>
      <% else %>
        <li>
          <%= link_to('Login', new_user_session_path)  %>  
          <%= link_to('Sign up', new_user_registration_path) %>
        </li>
      </ul>
    <% end %>
  ...

application.hmtl.erb_spec.rb:

require 'spec_helper'

describe "layouts/application.html.erb" do

  context "when user is signed in" do
    before :each do
      view.stub(:user_signed_in?) { true }

      current_user = double()
      current_user.stub(:username) { "Joe" }
      render
    end

    it "displays logout link" do
      expect(rendered).to have_link 'Logout'
    end

    it "displays username" do
      expect(rendered).to have_content 'Joe'
    end

    ...

  end
end

I get an error:

 Failure/Error: render
 ActionView::Template::Error:
   undefined method 'authenticate' for nil:NilClass

in line with <%= current_user.username %>

So it looks like this username stub doesn't work, any idea what's wrong here?

Upvotes: 2

Views: 2215

Answers (1)

Marcin Doliwa
Marcin Doliwa

Reputation: 3659

I solved this:

  view.stub(:user_signed_in?) { true }
  view.stub(:current_user) { FactoryGirl.build(:user, username: "Joe") } 

Upvotes: 6

Related Questions