Rails: Unit testing a before_create?

…衆ロ難τιáo~ 提交于 2019-12-21 05:51:10

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/993941/rails-unit-testing-a-before-create

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!