Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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 :)

like image 269
nfm Avatar asked Apr 06 '11 08:04

nfm


2 Answers

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
like image 83
Pan Thomakos Avatar answered Oct 18 '22 19:10

Pan Thomakos


You might like the shoulda callback matchers.

like image 27
Patrick Reiner Avatar answered Oct 18 '22 19:10

Patrick Reiner