Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 358
montrealmike Avatar asked Oct 12 '11 16:10

montrealmike


3 Answers

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
like image 115
ErsatzRyan Avatar answered Nov 07 '22 07:11

ErsatzRyan


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
like image 45
Kevin B Avatar answered Nov 07 '22 07:11

Kevin B


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

like image 12
charlesdeb Avatar answered Nov 07 '22 07:11

charlesdeb