Rspec生成的规范失败了

时间:2012-11-28 09:22:17

标签: ruby-on-rails rspec rspec-rails

我已将以下内容添加到我的application.rb文件

config.generators do |g|
    g.test_framework :rspec,

        :fixtures => true,
        :view_specs => false,
        :helper_specs => false,
        :routing_specs => false,
        :controller_specs => true,
        :request_specs => true

    g.fixture_replacement :factory_girl, :dir => "spec/factories"
end

然后我用

生成了一个控制器
$rails g controller home index

这在spec / controllers / home_controller_spec.rb中生成了如下所示的规范

describe HomeController do

  describe "GET 'index'" do
    it "returns http success" do
      get 'index'
      response.should be_success
    end
  end

end

这是rSpec生成的默认代码。我访问时可以看到该页面

http://localhost:3000/home/index 

在我的浏览器中

然后当我跑

$bundle exec rspec

我收到此错误

/Applications/MAMP/htdocs/2012/myapp/spec/controllers/home_controller_spec.rb:3:in `<top (required)>': uninitialized constant HomeController (NameError)
from /Users/bobwood/.rvm/gems/ruby-1.9.3-p194@myapp/gems/rspec-core-2.10.1/lib/rspec/core/configuration.rb:746:in `load'
from /Users/bobwood/.rvm/gems/ruby-1.9.3-p194@myapp/gems/rspec-core-2.10.1/lib/rspec/core/configuration.rb:746:in `block in load_spec_files'
from /Users/bobwood/.rvm/gems/ruby-1.9.3-p194@myapp/gems/rspec-core-2.10.1/lib/rspec/core/configuration.rb:746:in `map'
from /Users/bobwood/.rvm/gems/ruby-1.9.3-p194@myapp/gems/rspec-core-2.10.1/lib/rspec/core/configuration.rb:746:in `load_spec_files'
from /Users/bobwood/.rvm/gems/ruby-1.9.3-p194@myapp/gems/rspec-core-2.10.1/lib/rspec/core/command_line.rb:22:in `run'
from /Users/bobwood/.rvm/gems/ruby-1.9.3-p194@myapp/gems/rspec-core-2.10.1/lib/rspec/core/runner.rb:69:in `run'
from /Users/bobwood/.rvm/gems/ruby-1.9.3-p194@myapp/gems/rspec-core-2.10.1/lib/rspec/core/runner.rb:10:in `block in autorun'

这个错误意味着什么以及如何修复它?

编辑:routes.rb中有一行

get "home/index"

1 个答案:

答案 0 :(得分:1)

此错误表示您运行的规范文件不了解您的HomeController类 - 它不包括在内。

我认为您选择了一种在Rails中使用RSpec的更困难的方法。最简单的方法是使用rspec-rails。我查看了我的控制器规格,他们做的第一件事就是包含来自rspec-rails的rspec_helper.rb。我想这个文件用于加载测试所需的所有Rails类。

要安装rspec-rails,您只需将其添加到Gemfile并运行:

rails generate rspec:install