How do i get rid of @controller is nil error in my tests

I keep getting

 @controller is nil: make sure you set it in your test's setup method.

When I run my tests. Any idea what this means?


Solution 1:

when you inherit from ActionController::TestCase it infers the controller name from the test name if they do not match you have to use the setup part of test to set it.

So if you have

class PostsControllerTest < ActionController::TestCase
  def test_index
    #assert something
  end
end

Then @controller is auto instantiated to PostsController, however, if this were not the case and you had a different name you would need a setup as such

class SomeTest < ActionController::TestCase
  def setup
    @controller = PostController.new
  end
end

Solution 2:

I was in the process of upgrading to rspec 3 from the beta version on rails 4 and ran into this error. The problem turned out to be that our Controller spec describe statements used symbols instead of strings. Rspec was attempting to instantiate the symbol as the controller but they were in fact 'actions'.

#trys to set @controller = Index.new
describe SomeController do
  describe :index do
    before do
      get :index, format: :json
    end
    it { expect(response).to be_success}
  end
end

#works
describe SomeController do
  describe 'index' do
    before do
      get :index, format: :json
    end
    it { expect(response).to be_success}
  end
end

Solution 3:

ErsatzRyan answer is correct, however there is a small typo. Instead of

@controller = PostsController

it should be

@controller = PostsController.new

otherwise you get an error: undefined method `response_body='