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 :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With