简体   繁体   中英

How to write mock for Model method that calls a mailer

I'm trying to write a test for my Message model. This model has a method 'send_message':

def send_message
   ContactMailer.contact_mail(self.name, self.email, self.text, self.ip).deliver
end

In my rspec file I have the following:

mailer = double(ContactMailer)
mailer.should_receive(:contact_mail)

FactoryGirl.build(:message).send_message

I am receiving the following error:

 Failure/Error: mailer.should_receive(:contact_mail)
   (Double ContactMailer).contact_mail(any args)
       expected: 1 time with any arguments
       received: 0 times with any arguments

Any idea? Could it be because I'm not taking .deliver into account?

No, the issue is that you haven't told RSpec that ContactMailer should receive that message. The argument to double is just a way to "name" the double for documentation purposes, as discussed in https://github.com/rspec/rspec-mocks

You actually don't need a double in this case, as you can set the expectation directly on the ContactMailer class as follows:

ContactMailer.should_receive(:contact_mail)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM