测试使用Devise和RSpec的视图

Sin*_*hot 23 rspec ruby-on-rails devise

我想在将Devise的user_signed_in?方法添加到相关的视图模板后,尝试获得之前传递的rspec"视图规范" .模板看起来像这样:

<% if user_signed_in? %>
  Welcome back.
<% else %>
  Please sign in.
<% endif %>
Run Code Online (Sandbox Code Playgroud)

该视图规范经过看起来是这样的:

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
Run Code Online (Sandbox Code Playgroud)

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

  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)>'
Run Code Online (Sandbox Code Playgroud)

网络上有很多关于这个错误的引用,但是我还没有找到足够描述的答案,我可以再次通过测试.我认为这个问题与视图有关(正在与任何模型/控制器隔离测试)没有一些关键的Devise基础设施可用.您的建议表示赞赏.

此外,一旦测试通过,我将如何测试其他路径(用户已经登录)?我认为它会非常相似.谢谢.

Jes*_*ott 40

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

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

RSpec.configure do |config|
  config.include Devise::TestHelpers, :type => :controller
end
Run Code Online (Sandbox Code Playgroud)

但是既然你正在创建一个视图规范,你会想要这样的东西:

RSpec.configure do |config|
  config.include Devise::TestHelpers, :type => :controller
  config.include Devise::TestHelpers, :type => :view
end
Run Code Online (Sandbox Code Playgroud)