The RSpec way of doing this? Need help on validating block

Hello, I’m back again with more questions about mocks and how to do good
testing in general. Let’s say I’m writing this EmailSender class and I
want to make it totally awesomely tested with RSpec. Here’s how far I’ve
gotten so far:

require ‘net/smtp’

class EmailSender
def send_email
mailer.start(‘your.smtp.server’, 25) do |smtp|
smtp.send_message(“Yay! You got an email!”, ‘[email protected]’,
[email protected]’)
end
def

def mailer
Net::SMTP
end
end

describe EmailSender do
it “Should use Net::SMTP to send email”
es = EmailSender.new
es.mailer.should == Net::SMTP
MockSMTP = mock(“Net::SMTP”)
def es.mailer
MockSMTP
end
MockSMTP.should_receive(:start).with(‘your.smtp.server’, 25)
#but, er…wha?
end
end

So - not sure how to validate the part where “send_message” is called.
Is there a recommended way of doing this?

Yikes, left out the all-important call:

describe EmailSender do
it “Should use Net::SMTP to send email”
es = EmailSender.new
es.mailer.should == Net::SMTP
MockSMTP = mock(“Net::SMTP”)
def es.mailer
MockSMTP
end
MockSMTP.should_receive(:start).with(‘your.smtp.server’, 25)
#but, er…wha?
es.send_email
end
end

Sorry about that.

Ha! Don’t I feel silly. Just figured it out, I think.

Sebastian W. wrote:

Yikes, left out the all-important call:

describe EmailSender do
it “Should use Net::SMTP to send email”
es = EmailSender.new
es.mailer.should == Net::SMTP
MockSMTP = mock(“Net::SMTP”)
def es.mailer
MockSMTP
end
mock_smtp = mock(“smtp”)
MockSMTP.should_receive(:start).with(‘your.smtp.server’,
25).and_yield(mock_smtp)
mock_smtp.should_recieve(:send_message).with(“Yay! You got an
email!”, ‘[email protected]’,
[email protected]’)
es.send_email

end
end

Mission accomplished. :stuck_out_tongue:

Glad I could help!

“Sebastian W.” [email protected] writes:

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs