有没有一种好方法可以在 Rails 中使用 `:on` 参数测试 `before_validation` 回调?

发布于 2024-10-30 02:57:19 字数 512 浏览 5 评论 0原文

我有一个 before_validation :do_something, :on =>; :create 在我的模型之一中。

我想测试这种情况是否发生,并且不会发生在 :save 上。

有没有一种简洁的方法来测试这个(使用Rails 3,Mocha和Shoulda),而不需要做类似的事情:

context 'A new User' do
  # Setup, name test etc
  @user.expects(:do_something)
  @user.valid?
end

context 'An existing User' do
  # Setup, name test etc
  @user.expects(:do_something).never
  @user.valid?
end

在shoulda API中找不到任何东西,这感觉相当不干……

有什么想法吗?谢谢 :)

I have a before_validation :do_something, :on => :create in one of my models.

I want to test that this happens, and doesn't happen on :save.

Is there a succinct way to test this (using Rails 3, Mocha and Shoulda), without doing something like:

context 'A new User' do
  # Setup, name test etc
  @user.expects(:do_something)
  @user.valid?
end

context 'An existing User' do
  # Setup, name test etc
  @user.expects(:do_something).never
  @user.valid?
end

Can't find anything in the shoulda API, and this feels rather un-DRY...

Any ideas? Thanks :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

以歌曲疗慰 2024-11-06 02:57:19

我认为你需要改变你的方法。您正在测试 Rails 是否正常工作,而不是您的代码是否适用于这些测试。考虑测试您的代码。

例如,如果我有一个相当愚蠢的类:

class User
  beore_validation :do_something, :on => :create

  protected

  def do_something
    self.name = "#{firstname} #{lastname}"
  end
end

我实际上会像这样测试它:

describe User do
  it 'should update name for a new record' do
    @user = User.new(firstname: 'A', lastname: 'B')
    @user.valid?
    @user.name.should == 'A B' # Name has changed.
  end

  it 'should not update name for an old record' do
    @user = User.create(firstname: 'A', lastname: 'B')
    @user.firstname = 'C'
    @user.lastname = 'D'
    @user.valid?
    @user.name.should == 'A B' # Name has not changed.
  end
end

I think you need to change your approach. You are testing that Rails is working, not that your code works with these tests. Think about testing your code instead.

For example, if I had this rather inane class:

class User
  beore_validation :do_something, :on => :create

  protected

  def do_something
    self.name = "#{firstname} #{lastname}"
  end
end

I would actually test it like this:

describe User do
  it 'should update name for a new record' do
    @user = User.new(firstname: 'A', lastname: 'B')
    @user.valid?
    @user.name.should == 'A B' # Name has changed.
  end

  it 'should not update name for an old record' do
    @user = User.create(firstname: 'A', lastname: 'B')
    @user.firstname = 'C'
    @user.lastname = 'D'
    @user.valid?
    @user.name.should == 'A B' # Name has not changed.
  end
end
转身以后 2024-11-06 02:57:19

您可能喜欢 shoulda 回调匹配器

You might like the shoulda callback matchers.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文