Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MiniTest Authentication

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.
like image 758
miler350 Avatar asked Sep 25 '22 17:09

miler350


1 Answers

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.

like image 94
Oleg Avatar answered Oct 18 '22 11:10

Oleg