Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
679 views
in Technique[技术] by (71.8m points)

ruby on rails - Testing Views that use Devise with RSpec

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...