【问题标题】:View renders correctly in browser but tests fail on helper method?查看在浏览器中正确呈现,但辅助方法测试失败?
【发布时间】:2011-10-01 11:29:45
【问题描述】:

我有一个简单的视图和一个定义标题的助手。如果我在浏览器中打开视图,一切正常,但 rspec 测试失败。这是我所拥有的:

这是我的测试:

describe PagesController do
  render_views

  before(:each) do
    @base_title = "RoR Sample App"
  end

  describe "GET 'home'" do
    it "should be successful" do
      get 'home'
      response.should be_success
    end

    it "should have the right title" do
      get 'home'
      response.should have_selector("title",
                                    :content => @base_title + " | Home")
    end
  end
end

页面控制器:

class PagesController < ApplicationController
  def home
    @title = "Home"
  end

  def contact
    @title = "Contact"
  end

  def about
    @title = "About"
  end

  def help
    @title = "Help"
  end
end

帮手:

module ApplicationHelper
  # Return a title on a per-page basis.
  def title
    base_title = "RoR22 Sample App"
    if @title.nil?
      base_title
    else
      "#{base_title} | #{@title}"
    end
  end
end

还有观点:

<!DOCTYPE html>
<html>
<head>
  <title><%= title %></title>
  <%= stylesheet_link_tag :all %>
  <%= javascript_include_tag :defaults %>
  <%= csrf_meta_tag %>
</head>
<body>

<%= yield %>

</body>
</html>

这一切都在浏览器中正确呈现,但是当它到达&lt;%= title %&gt; 行时测试失败。

 1) PagesController GET 'home' should be successful
     Failure/Error: get 'home'
     ActionView::Template::Error:
       undefined local variable or method `title' for #<#<Class:0xabf0b1c>:0xabeec18>
     # ./app/views/layouts/application.html.erb:4:in `_app_views_layouts_application_html_erb___418990135_90147100_123793781'
     # ./spec/controllers/pages_controller_spec.rb:12:in `block (3 levels) in <top (required)>'

知道我做错了什么吗?

【问题讨论】:

    标签: ruby-on-rails view rspec helper


    【解决方案1】:

    这是 spork 的一个已知问题。您可以在 prefork 块中使用此解决方法:

    Spork.trap_method(Rails::Application, :reload_routes!)
    Spork.trap_method(Rails::Application::RoutesReloader, :reload!)
    

    【讨论】:

    【解决方案2】:

    那是你的application.html.erb。它在PagesHelper 中看不到该方法,您需要将该方法放入您的ApplicationHelper 中。只有你的PagesController 渲染的视图才能看到PagesHelper。在你的助手中明确添加return 是个好主意。

    【讨论】:

    • 当我把它放在 ApplicationHelper 中时,我得到了同样的错误。我必须明确告诉 rspec 看那里吗?
    • 在您的声明中明确添加return,更新答案
    • 是的,这是一个很好的观点。关于为什么它也看不到ApplicationHelper 有什么想法吗?
    【解决方案3】:

    最终的问题是我使用Spork gem 来加快我的测试速度,而无论出于何种原因spork 没有注册ApplicationHelper 已更改。

    解决方案只是重新启动 spork gem 并重新运行测试。

    【讨论】:

    • 您所说的“重启”spork 到底是什么意思?我该怎么做?
    • 如果您使用spork rspec --bootstrap 之类的命令启动 spork,则终止该进程 (CTRL+C) 并重新启动
    猜你喜欢
    • 1970-01-01
    • 2015-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多