Sunday, 17 May 2015

Writing specs for OmniAuth using Rspec

Recently, I used omniauth to implement google login in my rails application. Integrating and getting omniauth to work is pretty easy, if you are facing problems with that, you can check out another blog post which talks about just that. Now that you have knowledge of how omniauth will work in your project, you might want to write some specs for the same!

Here is where it gets a little tricky, for you to write specs for omniauth you'll have to mock it and insert omniauth.hash in the request environment.

Open your rails_helper.rb and add the following code to it.

OmniAuth.config.test_mode = true
omniauth_hash = { 'provider' => 'google_oauth2',
                    'uid' => '12345',
                    'info' => {
                        'name' => 'Tony Stark',
                        'email' => 'tony@stark.com',
                        'nickname' => 'Iron Man'
                    },
                    'extra' => {'raw_info' =>
                                    { 'location' => 'New York',
                                      'gravatar_id' => '123456789'
                                    }
                    }
  }
OmniAuth.config.add_mock(:google_oauth2, omniauth_hash)

Now whenever you need the omniauth hash in your specs, all you need to do is to call this line of code. After that your spec might look like this

before do
  request.env['omniauth.auth'] = OmniAuth.config.mock_auth[:google_oauth2]
end

it 'should redirect to admin user' do
  get :create, :provider => :google_oauth2
  expect(response).to redirect_to(User.last)
end

No comments:

Post a Comment