kush
kush

Reputation: 16928

Rails: Unit testing a before_create?

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 it's saved.

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

Upvotes: 4

Views: 1820

Answers (1)

user120587
user120587

Reputation:

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)

Upvotes: 4

Related Questions