Skip to content

Instantly share code, notes, and snippets.

@cantremember
Created March 23, 2012 05:25
Show Gist options
  • Save cantremember/2167235 to your computer and use it in GitHub Desktop.
Save cantremember/2167235 to your computer and use it in GitHub Desktop.
silly mocking in RSpec
def expect_raise(type=Spec::Mocks::MockExpectationError, &block)
abort 'block must be provided' unless block_given?
block.should raise_error(type)
end
specify "the basics" do
@mock.should_receive :hello
@mock.should_not_receive :goodbye
@mock.hello
expect_raise { @mock.stay }
expect_raise { @mock.goodbye }
end
specify "how many times, and with what" do
@mock.should_receive(:one).once.with(1)
@mock.one 1
@mock.should_receive(:string).exactly(1).times.with(an_instance_of(String))
@mock.string 'a string'
@mock.should_receive(:anything).exactly(3).times.with(any_args())
@mock.anything
@mock.anything :again
@mock.anything :third, 'time'
@mock.should_receive(:array_ish).with(duck_type(:each, :find, :size))
@mock.array_ish [:item]
end
specify "what i return, raise or throw" do
@mock.should_receive(:get_one).and_return(1)
@mock.should_receive(:put_one).with(1)
@mock.put_one @mock.get_one
@mock.should_receive(:increment).any_number_of_times.with(instance_of(Fixnum)).and_return {|i| i + 1 }
@mock.increment(1).should equal(2)
@mock.should_receive(:raises_string).and_raise('something runtime')
expect_raise(RuntimeError) { @mock.raises_string }
@mock.should_receive(:pitch).and_throw(:ball)
lambda { @mock.pitch }.should throw_symbol(:ball)
end
specify "yielding in a complex fashion" do
@mock.should_receive(:gimmee).exactly(3).times.and_yield(:x)
holder = []
@mock.gimmee {|value| holder << value }
holder.should eql([:x])
2.times { @mock.gimmee {|value| holder << value } }
holder.should eql([:x, :x, :x])
end
specify "validation via closure" do
(@mock.should_receive(:threely) do |value|
value.to_s.size.should eql(3)
end).exactly(3).times
@mock.threely 'x' * 3
@mock.threely :key
@mock.threely 333
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment