开发者

View renders correctly in browser but tests fail on helper method?

开发者 https://www.devze.com 2023-03-18 19:51 出处:网络
I have a simple view and a helper that defines the title. Everything works fine if I pull up the view in the browser, but the rspec tests fail. Here\'s what I have:

I have a simple view and a helper that defines the title. Everything works fine if I pull up the view in the browser, but the rspec tests fail. Here's what I have:

Here are my tests:

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

The Pages Controller:

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

  def contact
    @title = "Contact"
  end

  def about
    @title = "About"
  end

  def help
    @title = "Help"
  end
end

The helper:

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

And the view:

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

<%= yield %>

</body>
</html>

It all renders properly in the browser, but the tests fail when it gets to <%= title %> line.

 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_htm开发者_开发知识库l_erb___418990135_90147100_123793781'
     # ./spec/controllers/pages_controller_spec.rb:12:in `block (3 levels) in <top (required)>'

Any idea what I'm doing wrong?


This is a known issue with spork. You can use this workaround in your prefork block:

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


That's your application.html.erb. It can't see that method in the PagesHelper, you need to put that method in your ApplicationHelper. Only the views rendered by your PagesController can see PagesHelper. And it's a good idea to explicitly add return in your helpers.


It ends up the problem is that I was using the Spork gem to speed up my testing and for whatever reason spork wasn't registering that the ApplicationHelper had changed.

The solution was simply to reboot the spork gem and rerun the tests.

0

精彩评论

暂无评论...
验证码 换一张
取 消