I'm new to MiniTest. Most of the testing is easy to grasp as it is Ruby code and also has Rspec-style readability. I am, however, having trouble with authentications. As with any app, most controllers are hidden behind some sort of authentication, the most common being authenticate_user
to ensure that a user is logged in.
How do I test a session
-> user is logged in? I am using authentication from scratch not devise.
I do have this as a reference: https://github.com/chriskottom/minitest_cookbook_source/blob/master/minishop/test/support/session_helpers.rb
But not quite sure how to implement it.
Let's use this as an example controller:
class ProductsController < ApplicationController
before_action :authenticate_user
def index
@products = Product.all
end
def show
@product = Product.find(params[:id])
end
end
How would my test look in these basic instances?
test "it should GET products index" do
# insert code to check authenticate_user
get :index
assert_response :success
end
test "it should GET products show" do
# insert code to check authenticate_user
get :show
assert_response :success
end
#refactor so logged in only has to be defined once across controllers.
Are you using your custom authentication methods? If so you can pass needed session variables as a third param to request method:
get(:show, {'id' => "12"}, {'user_id' => 5})
http://guides.rubyonrails.org/testing.html#functional-tests-for-your-controllers
Otherwise, if you use any authentication library it usually provides some helper methods for testing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With