Reputation: 1421
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.
Upvotes: 5
Views: 1626
Reputation: 214
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.
Upvotes: 2
Reputation: 2113
You need to include devise test helpers and then you can use devise helpers just like in controller.
I.E:
require 'test_helper'
class ProtectedControllerTest < ActionController::TestCase
include Devise::TestHelpers
test "authenticated user should get index" do
sign_in users(:foo)
get :index
assert_response :success
end
test "not authenticated user should get redirect" do
get :index
assert_response :redirect
end
end
Also check out this:
How To: Test controllers with Rails 3 and 4 (and RSpec)
Upvotes: 2