How can I test a Ruby command-line program that communicates with a web service?

偶尔善良 提交于 2019-12-05 12:57:57

Aruba provides a mode that lets you run things "in process" that will allow you to use WebMock or VCR. Here's a blog post explaining how to do that:

http://georgemcintosh.com/vcr-and-aruba/

Alternately, you can consider writing a new binary that first loads VCR or WebMock, and then loads and executes your main binary, and have your test run this binary.

You could use vcr (cf. https://github.com/vcr/vcr)

It will turn your json response into a fixture.

I will copy the beginning of their Readme so you can get the idea:


require 'rubygems'
require 'test/unit'
require 'vcr'

VCR.configure do |c|
  c.cassette_library_dir = 'fixtures/vcr_cassettes'
  c.hook_into :webmock # or :fakeweb
end

class VCRTest < Test::Unit::TestCase
  def test_example_dot_com
    VCR.use_cassette('synopsis') do
      response = Net::HTTP.get_response(URI('http://www.iana.org/domains/reserved'))
      assert_match /Example domains/, response.body
    end
  end
end

Run this test once, and VCR will record the http request to fixtures/vcr_cassettes/synopsis.yml. Run it again, and VCR will replay the response from iana.org when the http request is made. This test is now fast (no real HTTP requests are made anymore), deterministic (the test will continue to pass, even if you are offline, or iana.org goes down for maintenance) and accurate (the response will contain the same headers and body you get from a real request).

Command line programs take parameters, so I'd write the program to take a URL as an arg that points to whatever service you want. Then I'd make a test version of your web service, using seed data that doesn't change. Then I'd write the cucumber tests to call the program with the test URL, and test against the expected data.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!