开发者

Is there a good way to test `before_validation` callbacks with an `:on` argument in Rails?

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

I want to t开发者_如何学Goest 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 :)


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


You might like the shoulda callback matchers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜