Rails:单元测试before_create吗?

时间:2021-04-18 01:20:57

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

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

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.

但这并不奏效,因为专辑。如果保存,permalink将不会返回值。

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

有办法测试before_create吗?我应该在控制器层做这个吗?

1 个解决方案

#1


4  

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

简而言之,它提到您可以使用send方法调用回调,回调作为它的参数。在这种情况下,可以通过使用强制相册调用before_create回调

album.send(:before_create)

#1


4  

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

简而言之,它提到您可以使用send方法调用回调,回调作为它的参数。在这种情况下,可以通过使用强制相册调用before_create回调

album.send(:before_create)