views:

237

answers:

1

Is there a standard or best-practices way to test that an action in rails is returning the correct text? For example, I have a simple action that is used for doing ajax validation that does the following:

def get_object_id
  if params[:id].blank?
    return render(:text => -1, :layout => false)
  end

  my_object = MyObject.find_by_id(params[:id].strip)

  # If the object is valid return the object id
  if my_object and my_object.active?
    return render(:text => my_object.id, :layout => false)
  end

  # Otherwise, return -1
  return render(:text => -1, :layout => false)
end

Right now, I'm using the @response object in my tests ... i.e.:

def test_get_object_id_returns_invalid_for_non_existent_id
  # Act
  get :get_object_id, :id => 999

  # Assert
  assert_response :success
  assert_equal "-1", @response.body
end

But, though being mostly new to rails, what I have seen so far seems to suggest that there's probably a better way to do this other than checking @request.body.

So, my question to you ruby experts is: Is this the best way?

+2  A: 

I think your spot on already.

assert_select only really works for XML content, so for other formats you have to roll your own. I would probably add a named assertion method to ActionController::TestCase if I was doing a lot of these.

e.g.

def assert_response_equals(v)
  assert_equal v.to_s, @response.body, "Expected response body to be #{v.inspect}"
end

This would allow you to skip the quotes.

cwninja
That's a good idea. Did you mean ActionController::TestCase instead of ActionController::TestClass? I can't seem to find any documentation on the latter.
jerhinesmith
Oops, corrected.
cwninja