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

nfm*_*nfm 6 unit-testing shoulda mocha.js ruby-on-rails-3

我有一个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
Run Code Online (Sandbox Code Playgroud)

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

有任何想法吗?谢谢 :)

Pan*_*kos 9

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

例如,如果我有这个相当无聊的类:

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

  protected

  def do_something
    self.name = "#{firstname} #{lastname}"
  end
end
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)