Skip to content

Instantly share code, notes, and snippets.

@kalarani
Last active October 28, 2015 18:30
Show Gist options
  • Select an option

  • Save kalarani/38730aba30049d1fd667 to your computer and use it in GitHub Desktop.

Select an option

Save kalarani/38730aba30049d1fd667 to your computer and use it in GitHub Desktop.
Use of Mocks in Unit Tests
File.write(‘sample_file.txt’, reversed_string)
expect(File).to receive(:write).with('sample_file.txt', expected_string)
class Post
def submit
begin
EmailService.send_mail @title, @author
rescue
Admin.notify
end
end
end
expect(EmailService).to receive(:send_mail).with('New post', 'someone')
require './post.rb'
require './email_service.rb'
describe Post do
describe '#submit' do
it 'should send mail' do
post = Post.new({:title => 'New post', :author => 'someone'})
expect(EmailService).to receive(:send_mail).with('New post', 'someone')
post.submit
end
end
end
require './post.rb'
require './email_service.rb'
require './admin.rb'
describe Post do
describe '#submit' do
it 'should notify admin if sending email fails' do
post = Post.new({:title => 'New post', :author => 'someone'})
expect(EmailService).to receive(:send_mail).and_throw('Something went wrong!')
expect(Admin).to receive(:notify)
post.submit
end
end
end
require './post.rb'
require './email_service.rb'
require './admin.rb'
describe Post do
describe '#submit' do
it 'should send mail' do
post = Post.new({:title => 'New post', :author => 'someone'})
expect(EmailService).to receive(:send_mail).with('New post', 'someone')
expect(Admin).to_not receive(:notify)
post.submit
end
end
end
class StringUtil
def reverse a_string
reversed_string = a_string.reverse
File.write(‘sample_file.txt’, reversed_string)
reversed_string
end
end
require './string_util'
describe StringUtil do
it 'should reverse a string' do
string_util = StringUtil.new
expected_string = 'tset a si sihT'
expect(File).to receive(:write).with('sample_file.txt', expected_string)
reversed_string = string_util.reverse('This is a test')
expect(reversed_string).to eq expected_string
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment