Reputation: 1558
I want to write an rspec unit test case, so that if internet connection exists it will connect to gmail, else it will raise exception.
I have tried to write something, but it server only one part of the problem. How could I write a unit test case so that it can test both, ie. will assert exception if unable to connect gmail else will test successful connection.
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
Method definition
def connect_to_gmail
begin
gmail = Gmail.new('[email protected]', 'Password123' )
rescue SocketError=>se
raise "Unable to connect gmail #{se}"
end
end
Upvotes: 0
Views: 900
Reputation: 5998
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
Upvotes: 2