View在浏览器中正确呈现,但是在helper方法上测试失败了?

时间:2011-07-08 17:43:01

标签: ruby-on-rails view rspec helper

我有一个简单的视图和一个定义标题的帮助器。如果我在浏览器中提取视图,一切正常,但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>

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

 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)>'

知道我做错了吗?

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

那是你的application.html.erb。它无法在PagesHelper中看到该方法,您需要将该方法放在ApplicationHelper中。只有PagesController呈现的视图才能看到PagesHelper。最好在助手中明确添加return

答案 2 :(得分:0)

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

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