Reputation: 8055
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?
Upvotes: 6
Views: 2936
Reputation: 71
You can use view_assigns
:
# asserts that the controller has set @cats to true
assert_equal @controller.view_assigns['cats'], true
Upvotes: 7
Reputation: 8055
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
Upvotes: 2