Rails:对 before_create 进行单元测试? [英] Rails: Unit testing a before_create?

查看:38
本文介绍了Rails:对 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.

专辑.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

但这不起作用,因为 album.permalink 在保存后不会返回值.

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

有没有办法测试before_create?我应该在控制器级别执行此操作吗?

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

推荐答案

我发现 您可能感兴趣的这篇博文.

简而言之,它提到您可以使用带有回调作为参数的发送方法自己调用回调.在这种情况下,您可以使用

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)

这篇关于Rails:对 before_create 进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆