Testing a REST full activeresource
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.

Ah, I was struggling with the same problem myself a few weeks ago. I found the tests (examples) with HttpMock in the code of the ActiveResource gem itself and used it within Rspec (although without the use of fixtures). I agree, no documentation, so it was a good idea to post this!!
It was a good example for active resource test. But when i try use this code i got the below error NameError: uninitialized constant MyResourceTest::Connections C:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:493:in `const_missing' C:/Rails/rails_client/test/unit/my_resource_test.rb:8:in `setup' C:/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:32:in `run' And am also newbie for rails, could you please help me for this issue