Search code examples
ruby-on-railsrspecrspec-rails

Rspec generated spec failing


I've added the following to my application.rb file

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

Then I generated a controller with

$rails g controller home index

This generated the specification in spec/controllers/home_controller_spec.rb which looks like this

describe HomeController do

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

end

This is the default code generated by rSpec. I can see the page when I visit

http://localhost:3000/home/index 

in my browser

Then when I run

$bundle exec rspec

I get this error

/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'

What does this error mean and how to I fix it?

EDIT: routes.rb has one line in it

get "home/index"

Solution

  • This error means that the spec file you run doesn't know about your HomeController class - it's not included.

    I think you chose a more difficult way to use RSpec in Rails. The easiest way is to use rspec-rails. I looked into my controller specs and the first thing they do is to include rspec_helper.rb, which comes from rspec-rails. I guess this file is used to load all the Rails classes you need for your test.

    To install rspec-rails all you need to do is add it to your Gemfile and run:

    rails generate rspec:install