3

作为 Rubyonrails 教程的一部分,我在尝试运行 Rspec 测试时不断收到此错误

失败:

1) GET 'about' 应该是成功的

 Failure/Error: get 'about'
 RuntimeError:
   @controller is nil: make sure you set it in your test's setup method.
 # ./spec/controllers/pages_controller_spec.rb:27:in `block (2 levels) in <top (required)>'

我已尽我所能尝试纠正它,但一切都证明是徒劳的。任何帮助将不胜感激。

这是我的 spec_helper.rb 文件

require 'rubygems'
require 'spork'

Spork.prefork do
end
Spork.each_run do
end

ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'

Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

RSpec.configure do |config|
config.include RSpec::Rails::ControllerExampleGroup
config.mock_with :rspec
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
end

pages_controller.rb 文件:

class PagesController < ApplicationController
 def home
 end

 def contact
 end

 def about
 end
 end

pages_controller_spec.rb 文件:

require 'spec_helper'

describe PagesController do
  render_views

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

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

end

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

routes.rb 文件:

SampleApp::Application.routes.draw do
  get "pages/home"

  get "pages/contact"

  get "pages/about"

end

顺便说一句,我运行 Spork 和自动测试没有问题。

4

1 回答 1

5

问题在于测试中的嵌套:该describe PagesController块仅包含前两个测试,而不是最后一个。

它应该如下所示:

describe PagesController do
  render_views

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

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

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

请参阅:我如何摆脱 @controller 在我的测试中是零错误

ps 我已经删除了render_views除了顶层describe块中的所有内容——您应该只需要为该块调用一次(请参阅规范)。

于 2013-01-10T21:52:48.803 回答