在RoR应用程序中使用RSpec进行测试 - 未初始化的常量

Ale*_*dre 5 rspec ruby-on-rails

我正在尝试通过RSpec测试我的Rails 3.2.3应用程序.它已安装(我已经测试了另一个应用程序并且运行良好)但它在Gemfile中不存在.这是代码spec/application_controller_spec.rb

    require "rspec"
    require_relative "../app/controllers/application_controller"

    describe ApplicationController do
      it "current_cart does something" do
        #app_controller  = ApplicationController.new
        pending
      end
    end
Run Code Online (Sandbox Code Playgroud)

以下命令返回错误:

alex@ubuntu:~/RubymineProjects/psg$ rspec spec
/home/alex/RubymineProjects/psg/app/controllers/application_controller.rb:1:in `<top (required)>': uninitialized constant ActionController (NameError)
    from /home/alex/RubymineProjects/psg/spec/application_controller_spec.rb:2:in `require_relative'
    from /home/alex/RubymineProjects/psg/spec/application_controller_spec.rb:2:in `<top (required)>'
    from /home/alex/.rvm/gems/ruby-1.9.3-p194/gems/rspec-core-2.11.1/lib/rspec/core/configuration.rb:780:in `load'
    from /home/alex/.rvm/gems/ruby-1.9.3-p194/gems/rspec-core-2.11.1/lib/rspec/core/configuration.rb:780:in `block in load_spec_files'
    from /home/alex/.rvm/gems/ruby-1.9.3-p194/gems/rspec-core-2.11.1/lib/rspec/core/configuration.rb:780:in `map'
    from /home/alex/.rvm/gems/ruby-1.9.3-p194/gems/rspec-core-2.11.1/lib/rspec/core/configuration.rb:780:in `load_spec_files'
    from /home/alex/.rvm/gems/ruby-1.9.3-p194/gems/rspec-core-2.11.1/lib/rspec/core/command_line.rb:22:in `run'
    from /home/alex/.rvm/gems/ruby-1.9.3-p194/gems/rspec-core-2.11.1/lib/rspec/core/runner.rb:69:in `run'
    from /home/alex/.rvm/gems/ruby-1.9.3-p194/gems/rspec-core-2.11.1/lib/rspec/core/runner.rb:8:in `block in autorun'
Run Code Online (Sandbox Code Playgroud)

文件ApplicationController.rb

 class ApplicationController < ActionController::Base
   def some_action
     #............
   end
Run Code Online (Sandbox Code Playgroud)

结束

即使我添加gem 'rspec'Gemfile也不会改变任何内容,错误仍然存​​在.

有什么想法吗?

ser*_*erg 7

在我的情况下,我需要添加rails_helper到spec文件或.rspec文件.

require 'spec_helper'
require 'rails_helper'

describe SomeController do
end
Run Code Online (Sandbox Code Playgroud)
# Or in the .rspec file:
--color
--require spec_helper
--require rails_helper
Run Code Online (Sandbox Code Playgroud)


tho*_*ler 6

这个require_relative在那里做什么?我使用rspec而不需要这个.实际上我的spec文件中唯一需要的是:

require 'spec_helper'
Run Code Online (Sandbox Code Playgroud)

(至少在大多数情况下,有一些文件需要特殊的东西,如"authlogic/test_case")

我对rspec的Gemfile条目如下所示:

group :development do
  gem 'rspec-rails'
end

group :test do
  gem 'rspec-rails'
  gem 'spork', '0.9.0.rc8'
end
Run Code Online (Sandbox Code Playgroud)

如果你当然不使用spork,你将不需要spork,但也许"rspec-rails"而不是"rspec"可能是你的问题.

  • 你运行"rails generate rspec:install"了吗?该文件是否存在于spec文件夹中? (2认同)