0

我想编写一个 rspec 单元测试用例,这样如果存在互联网连接,它将连接到 gmail,否则会引发异常。

我试图写一些东西,但它只解决了问题的一部分。我怎么能写一个单元测试用例,以便它可以测试两者,即。如果无法连接 gmail 将断言异常,否则将测试成功连接。

describe "#will create an authenticated gmail session" do
    it "should connect to gmail, if internet connection exists else raise exception" do
       @mail_sender = MailSender.new
       lambda { @mail_sender.connect_to_gmail}.should raise_error
    end
end

方法定义

def connect_to_gmail
    begin
      gmail = Gmail.new('abc@gmail.com', 'Password123' )
    rescue SocketError=>se
       raise "Unable to connect gmail #{se}"
    end
end
4

1 回答 1

2

You should use stubs or should_receive here.

case 1 (the behavior when internet connection exists):

it "should connect to gmail, if internet connection exists" do
  Gmail.should_receive(:new)
  @mail_sender = MailSender.new
  -> { @mail_sender.connect_to_gmail}.should_not raise_error
end

maybe you would like to return some object (Gmail.should_receive(:new).and_return(some_object)) and continue to work with this stubbed object

case 2 (the behavior when internet connection does not exist):

it "should raise error to gmail, if internet connection does not exist" do
  Gmail.stub(:new) { raise SocketError }
  @mail_sender = MailSender.new
  -> { @mail_sender.connect_to_gmail}.should raise_error
end

I hope this code helps you

于 2013-09-15T17:21:10.800 回答