Last week, one of the features requested for the new version of My Drinkaware app was to implement a Facebook login and signup.
The app was already using Devise for the Authentication, so implementing the feature using Omniauth was super easy.
If you’ve never done it before I recommend you read the Devise Omniauth wiki page and you’ll be ready in no time.
Writing the tests
Writing the tests for the Facebook login and signup is really easy as well, thanks to Omniauth test_mode.
Even though, at the moment, the client only wants to support Facebook authentication, the chances are that, in the future, Twitter or Gmail could be part of the scope.
So what I’ve ended up creating 2 helpers in my support/omniauth.rb file:
def set_omniauth(opts = {})
default = {:provider => :facebook,
:uuid => "1234",
:facebook => {
:email => "[email protected]",
:gender => "Male",
:first_name => "foo",
:last_name => "bar"
}
}
credentials = default.merge(opts)
provider = credentials[:provider]
user_hash = credentials[provider]
OmniAuth.config.test_mode = true
OmniAuth.config.mock_auth[provider] = {
'uid' => credentials[:uuid],
"extra" => {
"user_hash" => {
"email" => user_hash[:email],
"first_name" => user_hash[:first_name],
"last_name" => user_hash[:last_name],
"gender" => user_hash[:gender]
}
}
}
end
def set_invalid_omniauth(opts = {})
credentials = { :provider => :facebook,
:invalid => :invalid_crendentials
}.merge(opts)
OmniAuth.config.test_mode = true
OmniAuth.config.mock_auth[credentials[:provider]] = credentials[:invalid]
end
With this sweet setup, I can now have multiple defaults in my tests, which makes changes very clean:
background do
set_omniauth()
click_link_or_button 'Sign up with Facebook'
end
There you go, I hope it’ll help someone some day!