How to get rid of @controller - this is a mistake in my tests

I keep getting

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

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

+44
ruby-on-rails ruby-on-rails-3
12 Oct '11 at 16:05
source share
6 answers

when you inherit ActionController :: TestCase, it indicates the name of the controller from the name of the test, if they do not match, you must use the setup part of the test to install it.

So if you have

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

Then @controller automatically created on PostsController , however, if it is not, and you had a different name, you will need setup as such

 class SomeTest < ActionController::TestCase def setup @controller = PostController.new end end 
+76
Oct 12 '11 at 16:15
source share

I was in the process of upgrading to rspec 3 from beta on rails 4 and ran into this error. The problem turned out to be that our Controller specification describes expressions used instead of characters. Rspec tried to instantiate the character as a controller, but they were actually "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 
+13
Jun 20 '14 at 15:43
source share

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

 @controller = PostController 

he should be

 @controller = PostController.new 

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

+9
Oct 26
source share

Or you can simply do this:

 RSpec.describe PostsControllerTest, :type => :controller do # ... end 
+1
Oct 30 '15 at 13:37
source share

If the names match, and the @controller variable is still zero, try checking for errors in creating the controller instance. For me, I had a controller initialization method in which there was an error. For some reason, the controller was only zero in the test, instead of throwing an error when it was not created.

0
Feb 13 '17 at 18:03
source share

Check if you are completing the execution and you are completing correctly.

 RSpec.describe LeadsController, type: :controller do # All tests should come here end 
0
Oct 27 '17 at 12:50
source share



All Articles