Search code examples
ruby-on-rails-4rspec-railsrailstutorial.orgminitest

undefined method 'document' for nil:NilClass while running Rails-tutorial with rspec


I am following the railstutorial by Michael Hartl, and I don't understand the reason for failing tests in Chapter 5. The book used the minitest framework but I decided to use RSpec. To do this, I deleted the test folder and included rspec-rails in my Gemfile then ran bundle install and rails g rspec:install to generate my spec folders. However, there are some tests that I feel convenient running with minitest syntax such as assert_select in static_pages_controller_spec.rb file. Here is how my spec file looks like:

require "rails_helper"

RSpec.describe StaticPagesController, type: :controller do
  describe "GET #home" do
    it "returns http success" do
      get :home
      expect(response).to have_http_status(:success)
    end
    it "should have the right title" do
      get :home
      assert_select "title", "Ruby on Rails Tutorial Sample App"
    end
  end

  describe "GET #help" do
    it "returns http success" do
      get :help
      expect(response).to have_http_status(:success)
    end
    it "should have the right title" do
      get :help
      assert_select "title", "Help | Ruby on Rails Tutorial Sample App"
    end
  end

  describe "GET #about" do
    it "returns http success" do
      get :about
      expect(response).to have_http_status(:success)
    end
    it "should have the right title" do
      get "about"
      assert_select "title", "About | Ruby on Rails Tutorial Sample App"
    end
  end
end

When I run the tests with RSpec, this is what I get as the failure error:

StaticPagesController GET #home should have the right title
 Failure/Error: assert_select "title", "Ruby on Rails Tutorial Sample App"

 NoMethodError:
   undefined method `document' for nil:NilClass
# ./spec/controllers/static_pages_controller_spec.rb:11:in `block (3 levels)
in <top (required)>'

The same error message (No Method error) appears in each of the failing tests.

How can I fix it? Is there something I am doing wrong.


Solution

  • The reason for this error is that RSpec doesn't render views for controller specs by default. You can enable view rendering for a particular group of specs like this:

    describe FooController, type: :controller do
      render_views
    
      # write your specs
    end
    

    or you can enable it globally by adding this somewhere in your RSpec config:

    RSpec.configure do |config|
      config.render_views
    end
    

    See https://www.relishapp.com/rspec/rspec-rails/v/2-6/docs/controller-specs/render-views for more information.