使用 Devise 和 RSpec 测试视图 [英] Testing Views that use Devise with RSpec

查看:20
本文介绍了使用 Devise 和 RSpec 测试视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将 Devise 的 user_signed_in? 方法添加到相关视图模板后,我试图让之前通过的 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

添加对user_signed_in?的调用后产生的错误是:

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.

推荐答案

您收到的错误是因为您需要包含设计测试助手

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

通常您会将此(并且您可能已经拥有)添加到 spec/support/devise.rb

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

这篇关于使用 Devise 和 RSpec 测试视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆