Phlip
4/17/2009 8:07:00 PM
> I've run into the same problem and I did exactly what you're suggesting.
> You don't want to slow down your tests by making external API calls and
> since I'm assuming that you already know the behavior of the YouTube
> API, it makes sense to mimic that behavior in a mock class. Also, you
> will get great coverage results by doing this :)
When mocking an API, I often write a test like this:
def toast_youtuber
yt = YouTuber.new
puts yt.fetch('some_feed')
end
It's a "toast" - a temporary test that will toast your test run if you
accidentally integrate it. Switch it from "toast" to "test" in your editor,
run it, and inspect the output.
Switch it back to "toast", and copy the output into a sample file. Stash
that in your test/fixtures folder, and use it when you mock the wire
connection.
def test_youtuber_fetch
yt = YouTuber.new
yt.expects(:fetch).returns(File.read(RAILS_ROOT +
'/test/fixtures/youtuber.xml'))
yt.fetch('some_feed')
assert{ yt.feed == 'some_data' }
end
The .expects is a Mocha mock. Note we don't mock the whole object - just the
low-level part that hits the wire. (Unit tests that hit any outgoing wires
are not just slow, they are evil.)
Whenever you need to upgrade your mock data, just turn on the toast test
again and pull another real feed.
--
Phlip