O documento fornece dicas sobre como testar integrações com serviços externos de forma offline e rápida. Ele discute ferramentas como OmniAuth para autenticação offline, WebMock para evitar requests reais durante testes, e VCR para gravar responses para reprodução posterior.
14. OmniAuth
“OmniAuth is an authentication framework
that separates the concept of authentication
from the concept of identity, providing simple
hooks for any application to have one or
multiple authentication providers for a user”
https://rubygems.org/gems/omniauth
14
15. 1 # config/initializers/omniauth.rb
2 Rails.application.config.middleware.use OmniAuth::Builder do
3 provider :twitter, "key", "secret"
4 provider :facebook, "key", "secret", :scope => "email"
5 provider :linked_in, "key", "secret"
6 end
7
8 # test/test_helper.rb
9 OmniAuth.config.test_mode = true
10
11 OmniAuth.config.mock_auth[:twitter] = {
12 'uid' => '123545'
13 # etc.
14 }
15
16 # test/functional/signup_test.rb
17 test "..." do
18 get "/auth/twitter"
19 # ...
20 end
21
22 # test/functional/anything_test.rb
23 setup do
24 OmniAuth.config.add_mock(:facebook, :uid => '54321')
25 end
15
24. WebMock::NetConnectNotAllowedError: Real HTTP connections
are disabled. Unregistered request: GET http://graph.facebook.com:
443/oauth/access_token?
client_id=112121312&client_secret=56757657655&grant_type=cli
ent_credentials with headers {'Accept'=>'*/*', 'User-
Agent'=>'Ruby'}
You can stub this request with the following snippet:
stub_request(:get, "http://graph.facebook.com:443/oauth/
access_token?
client_id=112121312&client_secret=56757657655&grant_type=cli
ent_credentials").
with(:headers => {'Accept'=>'*/*', 'User-Agent'=>'Ruby'}).
to_return(:status => 200, :body => "", :headers => {})
24
31. VCR
“VCR provides a simple API to record and
replay your test suite's HTTP interactions. It
works with a variety of HTTP client libraries,
HTTP stubbing libraries and testing
frameworks”
https://rubygems.org/gems/vcr
31
32. 1 # test/test_helper.rb
2 VCR.config do |c|
3 c.cassette_library_dir = 'fixtures/vcr_cassettes'
4 c.stub_with :webmock
5 end
6
7 # test/integration/signup_test.rb
8 VCR.use_cassette('facebook_access_token') do
9 uri = URI('https://graph.facebook.com/oauth/access_token')
10 response = Net::HTTP.get_response(uri)
11 assert_match /access_token=.+/, response.body
12 end
32