作为Rubyonrails教程的一部分,当我尝试运行Rspec测试时,我一直收到这个错误
故障:
1( 获取"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
顺便说一句,我运行斯波克和自动测试没有问题。
问题在于测试中的嵌套: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在我的测试中为零错误
p.s.除了顶级describe
块中的一个之外,我已经取出了所有的render_views
——您应该只需要为该块调用一次它(请参阅规范(。