I've made an application with the omniauth-facebook gem. All of my rails test were passing, but after adding in code to check for an authenticated user for access to certain actions - some of my tests fail. How can I go about adding code to my tests to log in a "test" user so that I can simulate an authenticated user? Most of the google results showed examples for Rspec or Devise examples, but I've been using the default testing suite for Rails 5, so it's been difficult for me to find some examples of how to properly do this. Please let me know if you'd like me to provide any specific samples of my current tests. Nothing relevant came to mind to include since I'm not sure where to start with this.
So after reading through documentation here, and trying various things here's what I came up with...
test/test_helper.rb
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
OmniAuth.config.test_mode = true
OmniAuth.config.add_mock(:facebook, {:uid => '123456', info: { email: 'email_address_of_user_in_fixtures@gmail.com' }})
def sign_in_admin
Rails.application.env_config["omniauth.auth"] = OmniAuth.config.mock_auth[:facebook]
get auth_facebook_callback_path
end
end
test/controllers/restaurants_controller_test.rb
require 'test_helper'
class RestaurantsControllerTest < ActionDispatch::IntegrationTest
setup do
# I sign in an admin user, and proceed
sign_in_admin
@restaurant = restaurants(:mcdonalds)
end
# other test methods for actions ...
end
config/routes.rb
Rails.application.routes.draw do
#...
get 'auth/facebook/callback', to: 'sessions#create'
#...
end