Search code examples
rubytddruby-on-rails-5railstutorial.orgminitest

Accessing controller instance variables with Minitest


I'm trying to access the instance variables inside my controllers with minitest.

For example:

microposts_controller.rb:

def destroy
  p "*"*40
  p @cats = 42
end

How would I test the value of @cats with inside microposts_controller_test.rb with minitest?

I know I can submit the delete request from the browser and check my server logs and find:

"****************************************"
42

I read in another answer that I have access to an assigns hash with all the instance variables but it didn't work. I've also tried looking inside the controller object. Shown below:

microposts_controller.rb:

test "@cats should exist in destroy method" do 
  delete micropost_path(@micropost)
  p controller.instance_variables
  p assigns[:cats]
end

output:

[:@_action_has_layout, :@_routes, :@_request, :@_response, :@_lookup_context, :@_action_name, :@_response_body, :@marked_for_same_origin_verification, :@_config, :@_url_options]0:04
nil

I was expecting to see the @cats instance variable inside the controller object. I was also expecting to see 42 being output.

What am I missing here?


Solution

  • I had a before_action that checks to make sure the user is logged in, so the delete request was getting redirected.

    I also have a test helper that will put a valid user id into the session. Using that everything works as expected :)

    microposts_controller_test.rb:

    test "@cats should exist?" do
      log_in_as(users(:michael))
      delete micropost_path(@micropost)
      p controller.instance_variables
      p assigns[:cats]
    end
    

    test_helper.rb:

    def log_in_as(user)
      session[:user_id] = user.id
    end
    

    output:

    [:@_action_has_layout, :@_routes, :@_request, :@_response, :@_lookup_context, :@_action_name, :@_response_body, :@marked_for_same_origin_verification, :@_config, :@current_user, :@_params, :@micropost, :@cats, :@_url_options]
    42