[mocha-developer] Need some help in reducing my repetions in tests with Mocha

Jonathan Stott jonathan.stott at gmail.com
Sat May 3 08:08:31 EDT 2008

Hi All

I'm writing a gem to interact with the todoist JSON API and I'm using mocha to mock the server responses so I don't have to have a net connection to test and so I don't need to actually use my own API key anywhere.

Mostly I am interested in verifying that a correctly formatted URL has been sent, with the appropriate parameters, e.g API key have been sent. So I end up with expectations like so:

it "includes a token in the parameters" do
  http = mock()
  http.expects(:get).with { |url| 
    url.split("?",2).last =~ /token=#{@token}/ 

But the problem is, all my expectations basically feature the same lines of code (from http = mock() to Net::HTTP stubs) with only the "with" block changing.  But because it is the with block changing, I'm not sure how to create a method which will insert my changing block into the middle of the expectation call.

Well, I have a prototype method:

def web_stub(good=true,&block)
  http = mock()
  get = http.expects(:get)
  if block_given?
    get = yield get
  get.returns(good ? good_response : bad_response)

But this requires me to use the very ugly syntax of

web_stub do |get|
  get.with do |url| 
    url.split("?",2).first =~ /query$/

And I'd like to avoid the need for nested blocks if possible.

Any pointers on how to implement the method, or a better way of doing it in general would be appreciated!


More information about the mocha-developer mailing list