views:

18

answers:

1

Hi,

I see the following line in one of the test files in rails. It has a method called as any_instance. What is its use? Can someone please explain

http = Net::HTTP.new(Person.site.host, Person.site.port)
ActiveResource::Connection.any_instance.expects(:http).returns(http)
http.expects(:request).returns(ActiveResource::Response.new(""))

Thanks

+2  A: 

any_instance is a Mocha method. From the doc page:

Returns a mock object which will detect calls to any instance of this class.

Product.any_instance.stubs(:save).returns(false)
product_1 = Product.new
assert_equal false, product_1.save
product_2 = Product.new
assert_equal false, product_2.save
Daniel Vandersluis
@Daniel : I am confused on what this does. Can you please explain ..
Bragboy
Mocha is a stubbing and mocking framework, which is used in unit testing to simulate interacting with objects in a controlled manner. In the case of your code, a call to `ActiveResource::Connection#http` for any `ActiveResource::Connection` object accessed during the unit test will return the `http` object created in the first line.
Daniel Vandersluis