Skip to content

Instantly share code, notes, and snippets.

@freshtonic
Created March 2, 2010 23:39
Show Gist options
  • Save freshtonic/320111 to your computer and use it in GitHub Desktop.
Save freshtonic/320111 to your computer and use it in GitHub Desktop.
# I'm testing some code that translates HTTP query params from the front end
# into a query against a Solr via the Sunspot API. What I want to be able to
# do is unit test the query translation step *without* having to have Solr running.
# So I thought about mocking it out, but none of the mocking frameworks seem to
# be able to provide a way of mocking out something passed as a block.
# I have some HTTP query that my code 'executes' against Solr. It should be *exactly* equivalent
# to running the following query against Sunspot.
Sunspot.search(Scrape) do
with(:domain).equal_to("some.domain.name.com")
end
# What I want to be able to do is somehow mock 'self' within the block so that I can
# test that with(:domain).equal_to("some.domain.name.com") is executed.
# So far I haven't figured out how to do it with a mocking framework.
# I want to be able to say something like this (verbose for clarity, mock framework is RR)
mock(Sunspot).search(Scrape).is_called_with_block_that_executes do |_self|
_self.with(:domain).equal_to("some.domain.name.com")
end
# Any ideas?
# I realise I could hand code a mock Sunspot.search method, or perhaps
# mock the internal Sunspot DSL class but that feels dirty.
@freshtonic
Copy link
Author

freshtonic commented Dec 8, 2011 via email

@mmzoo
Copy link

mmzoo commented Dec 9, 2011

Hah! Thanks, I just were about to use

class SunspotSearchTestModel
  def self.search(&block)
    instance_eval(&block)
  end
end
SunspotSearchTestModel.should_receive(:keywords).with('john')

But your solution is really nicer. Thanks a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment