Search code examples
ruby-on-railstestingprivate-members

Rails: how to test before_save callbacks


Given a typical ActiveRecord model, I often have before_save callbacks that parse input, for instance taking something like time_string from the user and parsing it into a time field.

That setup might look like this:

before_save :parse_time
attr_writer :time_string

private
def parse_time
  time = Chronic.parse(time_string) if time_string
end

I understand that it's considered best practice to make callback methods private. However, if they're private, then you can't call them individually to test them in isolation.

So, for you seasoned Rails testers out there, how do you handle testing this kind of thing?


Solution

  • In Ruby, Private methods are still available via Object#send

    You can exploit this for your unit testing like so:

    project = Project.new
    project.time_string = '2012/11/19 at Noon'
    assert_equal(project.send(:parse_time), '2012-11-19 12:00:00')