Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Views that use Devise with RSpec

Tags:

I am trying to get a previously passing rspec "view spec" to pass after adding Devise's user_signed_in? method to the view template in question. The template looks something like this:

<% if user_signed_in? %>   Welcome back. <% else %>   Please sign in. <% endif %> 

The view spec that was passing looks something like this:

require "spec_helper"  describe "home/index.html.erb" do    it "asks you to sign in if you are not signed in" do     render     rendered.should have_content('Please sign in.')   end  end 

The error it produces after adding the call to user_signed_in? is:

  1) home/index.html.erb asks you to sign in if you are not signed in      Failure/Error: render      ActionView::Template::Error:        undefined method `authenticate' for nil:NilClass      # ./app/views/home/index.html.erb:1:in `_app_views_home_index_html_erb__1932916999377371771_70268384974540'      # ./spec/views/home/index.html.erb_spec.rb:6:in `block (2 levels) in <top (required)>' 

There are plenty of references to this error around the web, but I have yet to find an answer descriptive enough that I can get my test passing again. I believe the problem has something to do with the view (which is being testing in isolation from any models/controllers) not having some key Devise infrastructure available. Your suggestions are appreciated.

Also, once the test passes, how would I test the other path (user already signed in)? I presume it will be very similar. Thanks.

like image 525
SingleShot Avatar asked Oct 22 '12 05:10

SingleShot


2 Answers

The error you're receiving is because you need to include the devise test helpers

Generally you'll add this (and you might already have) to spec/support/devise.rb

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

But since you're creating a view spec, you'll want something like this:

RSpec.configure do |config|   config.include Devise::TestHelpers, :type => :controller   config.include Devise::TestHelpers, :type => :view end 
like image 85
Jesse Wolgamott Avatar answered Oct 26 '22 14:10

Jesse Wolgamott


Have a look at Rails Composer, this will guide you through a new rails project creation with options like testing, UI etc..

Create a sample project, cool thing is it will create all the test for you including view testing with devise. Then you can get an idea from those testing specs.

worked for me :D

HTH

like image 25
sameera207 Avatar answered Oct 26 '22 12:10

sameera207