Simple tweaks to make testing easier
Rails does a great job of making testing easier. There are still a few things you can do to simplify testing via selenium. I’ll show a quick monkeypatch that makes testing error messages much easier.
It’s taken me a while to get into it, but I’ve finally started creating tests with selenium. The first thing I noticed is that it can be a pain to verify that an error message is in the correct place. I already have a relatively DRY setup, I have a text_field_with_errors helper that includes the error message right by the text field and sets CSS classes correctly. It calls error_message_for to get the error message, which is really easy. Unfortunately, I still had problems testing.
error_message_for has a parameter to take a CSS class, but no way of taking an ID column. Fortunately, it is just a monkeypatch away!
module ActionView
module Helpers
module ActiveRecordHelper
def error_message_on(object, method, prepend_text = "", append_text = "", css_class = "formError",options={})
if errors = instance_variable_get("@#{object}").errors.on(method)
options[:class]=css_class
content_tag("div", "#{prepend_text}#{errors.is_a?(Array) ? errors.first : errors}#{append_text}", options)
end
end
end
end
end
If you drop the following into config.rb, you now get a fourth parameter to error_message_on which lets you select html attributes. by adding :id=>"error_for_#{object}_#{field}", you can now easily tell which error goes with which field. In selenium, your tests now look like
|verifyText|error_msg_job_location|This field can't be blank|
It’s simple, but also really easy and powerful. Thank goodness for ruby!
Posted by Mike Mangino on Friday, October 13, 2006