Test your sign in with social network feature with integration tests

Ruby on Rails / Testing

Option to sign in or sign up with Facebook, Twitter or any social network is a nice feature in every app. It’s obvious how to test such feature in unit tests but things become harder to test if we want to write acceptance tests. If you are not familiarized with acceptance tests yet I encourage you to read the previous article about that kind of tests.

Let’s get back to the main subject. Fortunately, OmniAuth gem authors took into account that we may want to test their gem in the integration part of our tests and they prepared proper code to turn the test mode for authorization.

Configuration

The first step is to let OmniAuth know that we are in the test mode:

OmniAuth.config.test_mode = true

Now it’s time to stub the response from given network. If you are using multiple networks then you will have to repeat this process multiple times and each time stub for your network response may look a little bit different than the stub for the previous network. I will prepare the response for LinkedIn:

user = FactoryBot.create :user
auth_info = double(first_name: user.first_name, last_name: user.last_name, email: user.email, image: 'image')
linkedin_auth = double(provider: user.provider, uid: user.uid, info: auth_info)

Your User model structure, or any other model where you keep current user data, may look different than mine so don’t simply copy and paste this code because it may not work. FactoryBot it’s a call from factory_bot gem which provides useful fixtures for Rails tests, you can check it here: https://github.com/thoughtbot/factory_bot

When we have our response stubbed we can let OmniAuth know that we want to use it:

OmniAuth.config.mock_auth[:linkedin] = linkedin_auth

And that’s it. You can now move this configuration to some helper method and reuse in your acceptance tests:

def linkedin_sign_in(user)
  auth_info = double(first_name: user.first_name, last_name: user.last_name, email: user.email, image: 'image')
  linkedin_auth = double(provider: user.provider, uid: user.uid, info: auth_info)
  OmniAuth.config.mock_auth[:linkedin] = linkedin_auth
end

Don’t forget to move this line:

OmniAuth.config.test_mode = true

to your spec_helper.rb or rails_helper.rb. You will be sure that you won’t perform real request during your tests.

Testing

Now you can simply click on the sign in button during your test and OmniAuth will simulate the whole process and your user will be automatically signed in with the data you provided in response stub. Happy testing!