Ensure method is called once during a test case

11 views
Skip to first unread message

Sven Dahlstrand

unread,
Oct 23, 2009, 8:46:14 AM10/23/09
to mocha-developer
Hello,

I want to test the UserObserver and make sure that
deliver_welcome_email is called when a user is saved.

class UserObserver < ActiveRecord::Observer
def after_create(user)
Mailer.deliver_welcome_email(user)
end
end

Here is my test case:

class UserObserverTest < ActiveSupport::TestCase
should 'should send welcome email when saved' do
user = Factory.build :user
Mailer.expects(:deliver_welcome_email).with(user)
user.save
end
end

Users are created in other tests as well and therefore
Mailer.deliver_welcome_email is called more than once and the test
fails. Is there a way to make sure that the method is called only once
during this particular test?

James Mead

unread,
Oct 26, 2009, 7:29:27 AM10/26/09
to mocha-d...@googlegroups.com
2009/10/23 Sven Dahlstrand <sven.da...@gmail.com>:

I'm a little unclear what the problem is. Which test is failing? And
what is the error message?

An expectation in one test should have no influence on behaviour in
other tests. The expectation you have declared in the following line
already requires the 'deliver_welcome_email' to be called *exactly*
once :-

Mailer.expects(:deliver_welcome_email).with(user)

Although you could make it more explicit by using 'once' :-

Mailer.expects(:deliver_welcome_email).once.with(user)

Cheers, James.

Reply all
Reply to author
Forward
0 new messages