Skip to content

Instantly share code, notes, and snippets.

@alenia
Created February 13, 2013 16:43
Show Gist options
  • Save alenia/4945954 to your computer and use it in GitHub Desktop.
Save alenia/4945954 to your computer and use it in GitHub Desktop.
A spec level overview of rspec_mocks and rspec_spies syntax
# When using the gems rspec_mocks and rspec_spies
class Widget
def a_method
'I am a method!'
end
end
describe Widget do
let(:item) {Widget.new}
context 'arguments' do
it 'works with returning multiple values based on passed in arguments' do
item.stub(:a_method).with(2).and_return { 'two!'}
item.stub(:a_method).with(3).and_return { 'three!'}
item.a_method(3).should == 'three!'
item.a_method(2).should == 'two!'
expect {item.a_method(1)}.to raise_error
end
it 'works with returning multiple values for a method with multiple args' do
item.stub(:a_method).with(anything, 'foo').and_return { 'three!'}
item.stub(:a_method).with(anything, 'bar').and_return { 'two!'}
item.a_method(1, 'foo').should == 'three!'
item.a_method(1, 'bar').should == 'two!'
expect {item.a_method(1, 'baz')}.to raise_error
end
it 'allows you to specify the number of arguments' do
item.stub(:a_method).with(anything, anything).and_return { 'win!'}
item.a_method(1,2).should == 'win!'
expect {item.a_method(2)}.to raise_error
expect {item.a_method(1,2,3)}.to raise_error
end
it 'blocks rock!' do
item.stub(:a_method).with(anything, anything) do |arg1, arg2|
"#{arg1} is a thing! so is #{arg2}."
end
item.a_method('Frog', 'dog').should == "Frog is a thing! so is dog."
end
end
it 'allows you to stub methods that do not exist' do
item.stub(:a_method_that_doesnt_exist)
expect { item.a_method_that_doesnt_exist }.not_to raise_error
end
it 'stubbing class methods does not overwrite instance methods' do
Widget.stub(:widge).and_return('widged')
Widget.widge.should == 'widged'
Widget.new.a_method.should == 'I am a method!'
end
describe 'spies' do
it 'allows you to spy on things' do
item.stub(:a_method).with(anything)
item.a_method('foooo!')
item.should have_received(:a_method).with('foooo!')
end
it 'allows you to spy and still call the original method' do
item.stub(:a_method).and_call_original
item.a_method.should == 'I am a method!'
item.should have_received(:a_method)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment