Search code examples
ruby-on-railsauthenticationrspecdevisetdd

Testing devise views with rspec


I have generated Devise's views running rails g devise:views and would now like to test them.

This is what I have come up with:

require 'spec_helper'

describe "devise/sessions/new" do
    before do
        render
    end

    it "renders the form to log in" do
        rendered.should have_selector("form", action: user_session_path, method: :post) do |form|

        end
    end
end

For the render statement it gives me undefined local variable or method 'resource'. After googling around I found that I should add

@user.should_receive(:resource).and_return(User.new)

before the render statement - but it still gives me the same error, and I am not really sure how to use it.

What am I doing wrong? Thanks for your help.


Solution

  • And whaddya know? I found this answer where someone had a similar problem. The solution is to include the following code in your application helper:

    def resource_name
      :user
    end
    
    def resource
      @resource ||= User.new
    end
    
    def devise_mapping
      @devise_mapping ||= Devise.mappings[:user]
    end
    

    This is necessary because devise is using certain helper methods in its controllers. If I access the views from my specs, however, these helper methods are not available, hence my tests fail. Putting these methods inside the application helper makes them accessible throughout the application, including my specs, and indeed the tests pass!