Posted by Bart ten Brinke Wed, 04 Jul 2007 13:49:28 GMT
Active Resources are nice, nut when you're trying to test your active resources , you're in for a long night. Luckally someone did a lot of the basic work for us. The HTTPMock class in ActiveResource is a very handy tool for testing your active resources. Unfortunately there is absolutely no documentation about how to use it, and it has some behaviour you might not expect. Therefore I present you with this code example.
The remote models of our REST connection live in Connections::IO::REST. When requesting the Employees via Connections::IO::REST::Employee.find(:all), we are actually requesting /employees.xml from our HTTPMock class. The HTTPMock class then just outputs the XML file of the testset we got from our friend which wrote the REST-connector we are connecting to. In the example, this is: /test/remote_fixtures/connector/employees.xml
class IORestConnectionTest < Test::Unit::TestCase
def setup
@pre = Connections::IO::REST
@mock_url = 'http://localhost/'
@headers = {"User-Agent"=>"Moves", "Accept-Encoding"=>"deflate", "Content-Type"=>"application/xml"}
ActiveResource::HttpMock.respond_to do |mock|
mock.get "/employees.xml", @headers, ioconnect_resources('employees')
mock.get "/clients.xml" , @headers, ioconnect_resources('clients')
end
# Overwrite all site URLS
@pre::Resource.site = @mock_url
end
def ioconnect_resources(name)
path = File.join(RAILS_ROOT, "test", "remote_fixtures", "ioconnect", "#{name.to_s}.xml")
return nil unless File.exists?(path)
File.read path
end
def teardown
ActiveResource::HttpMock.reset!
end
def test_should_find_all_employees_via_rest
employees = @pre:Employee.find(:all)
assert_equal employees.count, 20
end
end
One last note: HTTPMock was created to be as simple as possible. If you request something with a different header or parameters in the URL, it will return absolutely nothing. So if you get no response from your mock activeresource, be sure to check the headers you sent.
