简体   繁体   English

测试使用Devise和RSpec的视图

[英]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? 我想在添加Devise的user_signed_in?之后获得之前传递的rspec“视图规范” 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? 添加对user_signed_in?的调用后产生的错误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. 我认为这个问题与视图有关(正在与任何模型/控制器隔离测试)没有一些关键的Devise基础设施可用。 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 您收到的错误是因为您需要包含设计测试助手

Generally you'll add this (and you might already have) to spec/support/devise.rb 通常,您会将此(您可能已经拥有)添加到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

Have a look at Rails Composer , this will guide you through a new rails project creation with options like testing, UI etc.. 看看Rails Composer ,它将指导您完成一个新的rails项目创建,其中包括测试,UI等选项。

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 为我工作:D

HTH HTH

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM