If you ever had to deal with testing code dependent on external HTTP services like a REST API, you’re probably familiar with the VCR. It records HTTP requests and replays them during the tests in a deterministic manner.

Jorge Manrubia has applied to same idea but to any ruby object with the Impersonator gem. There are many cases where complex external services are not easy to mock or stub.

With Impersonator, you can call the object the first time and record the values in a YAML file. Next time, it replays the saved values.

Here is a quick rspec example:

describe Service, :impersonator do
  it 'answers to the ultimate question of life' do
    impersonator = Impersonator.impersonate(:answer_to_everything){ Service.new }
    expect(impersonator.answer_to_everything).to eq(42)
  end
end

The gem is quite new, but it seems interesting and I’m curious to see how it will evolve.