views:

54

answers:

2

I've read quiet a bit of documentation over the last few days about testing in Rails, I'm sitting down to write my first real test and not 100% sure how to tie what I have learned together to achieve the following functional test (testing a controller)

I need to send a GET request to a URL and pass 3 parameters (simple web-service), if the functionality works the keyword true is simply returned, otherwise the keyword false is returned - its in only value returned & not contained in any <div>, <span> or other tags.

The test should assert that if "true" is returned the test is successful.

This is probably very simple so apologies for such a non-challenging question.

If anyone could point me in the write direction on how I can get started, particularly how I can test the response, I'd be very grateful!

+1  A: 

Have you read A Guide to Testing Rails Applications? It's pretty good.

Your test is probably going to look something like:

def test_should_get_index
  get :index, :a => "1", :b => "2", :c => "3"
  assert_response :success
  assert_equal "true", @response.body
end
John
Thanks John, I have indeed - its very good as you say. I was not sure how to test the body of the response....was hitting a wall at this point. Most of the examples deal with parsing tags.
Jason
A: 

If it's a test of your own application, something like this can be done as a functional test or an integration test depending on your preference. Integration tests are more "real world" in that they use real URLs and routes, unlike functional tests which simply exercise particular controller actions.

For an external service, all you really need is to make use of Test::Unit or another framework like rspec or Cucumber as a wrapper for your test definitions.

Define the method that makes this GET request in a class of some kind, and then write a harness that tests it. For example:

def test_expected_response
  assert_equal 'true', MyHelper.make_call('param_a', 'param_b', 'param_c')
end

Obviously this test will fail unless MyHelper and MyHelper.make_call are properly defined, but that isn't too hard:

class MyHelper
  def make_call(a, b, c)
    # Call service using Net::HTTP, Curb, etc.
    # ...
    # Return answer
  end
end
tadman
Thanks Tadman, I like the class / harness model, very scalable! Just wondering where you would put the MyHelper class in the Rails directory structure (as in good practice place to put these test classes), in lib?
Jason
If you put them in app/models, they will be reloaded automatically when in the development environment, which can simplify debugging. If you put them in lib they're not cluttering up your model directory. Either should work.
tadman