|
|
Tools and techniques for BUILDING WEB SERVICES BACKED RUBY applications KRIS GONZALEZ GONZO@THOUGHTWORKS.COM
TWO COMMON CONCERNS What library should I use for external HTTP interactions? How do I build a reliable test harness for code which interacts with volatile services? Developing against volatile external services Implies a couple common concerns:
CHOOSE YOUR OWN WEB-VENTURE Net::HTTP Open-URI Mechanize HTTParty Faraday Several popular HTTP libraries:
FARADAY: A RACK-LIKE APPROACH TO OUTBOUND SERVICES RACK for inbound HTTP request response request response FARADAY for outbound HTTP MIDDLEWARE MIDDLEWARE MIDDLEWARE MIDDLEWARE
RACK MIDDLEWARE REFRESHER A basic Rack stack looks something like: Adding custom middleware is simple:
FARADAY MIDDLEWARE: ROLL YOUR OWN A basic Farady connection initialiser stack: Adding custom Faraday middleware is straightforward:
FARADAY MIDDLEWARE (cont’d) Example custom Faraday request middleware:
FARADAY MIDDLEWARE (cont’d) Example custom Faraday response middleware:
TESTING EXTERNAL SERVICES Tests should be deterministic, their outcomes predictable and repeatable External services tend towards volatility; difficult to test Stubbing out external services is the way you achieve deterministic testing of volatile external services.
TESTING EXTERNAL SERVICES (cont’d) Create an injectable proxy which intercepts and responds to service calls reliably Utilise a library which will intercept and reliably respond for you There are essentially two approaches two stubbing: VCR is a ruby lib which records the request/response cycle. Tests exercising code that makes outbound requests can reliably assume a known response.
VCR (cont’d) Consider this class which makes an outbound service call:
VCR (cont’d) We use a VCR cassette file to play back the service response during the test:
TURN THE VCR OFF: ARE YOUR SERVICES SANE? VCR-enabled tests do more than allow you to code against reliable services; they can serve as a canary for when the services go askance! VCR modality makes your tests doubly-powerful Running in “playback” mode (i.e. with VCR) tests your code Running in “off” mode tests the services themselves
TURN THE VCR OFF (cont’d) Add a configuration similar to this to your spec_helper.rb to enable VCR in three helpful modes: 1) Off: bypass VCR and run HTTP requests against real services Record: same as “Off”, but record the request/response cycle for future playback 3) Playback: intercept all HTTP requests with VCR, responding from recorded cassettes
¿PREGUNTAS? The following sample app on my Github uses the techniques and libraries discussed in this presentation: https://github.com/jimjamjoh/text-my-grub
Summary: Slide deck for a presentation on building web services-backed ruby apps given at the SF Ruby Meetup on Thursday, 25 Oct 2012.
| URL: |
No comments posted yet
Comments