继续得到@controller是零错误

时间:2013-01-10 21:23:34

标签: ruby ruby-on-rails-3

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

故障:

1)获取'关于'应该成功

 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和autotest没问题。

1 个答案:

答案 0 :(得分:4)

问题在于测试中的嵌套: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

请参阅:How do i get rid of @controller is nil error in my tests

P.S。除了顶级render_views块中的describe之外,我已取出所有{{1}} - 您只需要为该块调用一次(请参阅specs)。< / p>