views:

257

answers:

1

I am trying to test that a field is being generated properly by a callback, but I can't figure this one out.

album.rb

  before_create :generate_permalink

  private
  def generate_permalink
    @title = album.downcase.gsub(/\W/, '_')
    @artist = artist.downcase.gsub(/\W/, '_')
    self.permalink =  @artist + "-" + @title
  end

album_test.rb

  test "should return a proper permalink" do
    album = Album.new(:artist=>'Dead Weathers', :album=>'Primary Colours')
    album.save
    assert_equal "dead_weathers-primary_colours", album.permalink 
  end

But this doesn't work because album.permalink won't return the value if its saved.

Is there a way to test a before_create? Should I be doing this at the controller level?

+2  A: 

I found this blog post that might be of interest to you.

In short it mentions that you can call the callback yourself by using the send method with the callback as its parameter. In this case you can force album to call the before_create callback by using

album.send(:before_create)
Brandon Bodnár
thanks, that worked with: album.send(:generate_permalink)with the method name instead of :before_create
dMix
Oops, forgot to read the whole blog post, and was not at my home machine to test. Yeah, it is name of the method you want to call, not the call back. Apparently this is a hack for calling private methods.
Brandon Bodnár