Skip to main content
 首页 » 编程设计

ruby-on-rails之使用带有 RSpec 的设计测试 View

2024年12月31日14mfryf

在添加 Devise 的 user_signed_in? 后,我试图让之前通过的 rspec“查看规范”通过有问题的 View 模板的方法。模板看起来像这样:

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

传递的 View 规范如下所示:
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? 的调用后产生的错误是:
  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)>' 

网络上有很多关于这个错误的引用,但我还没有找到一个足够描述性的答案,我可以让我的测试再次通过。我相信这个问题与 View (正在与任何模型/ Controller 隔离测试)没有一些关键的设计基础设施可用。您的建议表示赞赏。

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

请您参考如下方法:

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

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

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

但是由于您正在创建 View 规范,因此您需要这样的东西:
RSpec.configure do |config| 
  config.include Devise::TestHelpers, :type => :controller 
  config.include Devise::TestHelpers, :type => :view 
end