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

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
3da512875f3295be2d577fa70b3493b4?d=identicon&s=25 Sebastian W. (globulus)
on 2008-12-04 08:58
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!", 'your@mail',
'other@mail')
    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?
3da512875f3295be2d577fa70b3493b4?d=identicon&s=25 Sebastian W. (globulus)
on 2008-12-04 08:59
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.
3da512875f3295be2d577fa70b3493b4?d=identicon&s=25 Sebastian W. (globulus)
on 2008-12-04 09:07
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!", 'your@mail',
'other@mail')
>       es.send_email
>>   end
>> end

Mission accomplished. :P
42172acdf3c6046f84d644cb0b94642c?d=identicon&s=25 Pat Maddox (pergesu)
on 2008-12-04 18:53
(Received via mailing list)
Glad I could help!

"Sebastian W." <lists@ruby-forum.com> writes:
This topic is locked and can not be replied to.