Skip to content

Instantly share code, notes, and snippets.

@pithyless
Forked from Peeja/group_of_thingies.rb
Created February 8, 2012 08:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pithyless/1766902 to your computer and use it in GitHub Desktop.
Save pithyless/1766902 to your computer and use it in GitHub Desktop.
Test a block in Ruby
class GroupOfThingies
attr_accessor :thingies
# Use like this:
#
# group_of_thingies = GroupOfThingies.new
# group_of_thingies.each do |thing|
# puts "Check out this awesome thing: #{thing}!"
# end
#
# or you can exclude a thing
#
# group_of_thingies = GroupOfThingies.new
# group_of_thingies.each(:except => bad_thing) do |thing|
# puts "This is a good thing: #{thing}!"
# end
#
def each(options={})
(thingies || []).each do |thing|
yield(thing) unless options[:except] == thing
end
end
end
class MockBlock
def to_proc
lambda { |*a| call(*a) }
end
end
describe GroupOfThingies do
subject { GroupOfThingies.new }
describe 'with a bunch of thingies' do
let(:mock_thing_1) { mock 'thing 1' }
let(:mock_thing_2) { mock 'thing 2' }
let(:mock_thing_3) { mock 'thing 3' }
let(:thingies) { [mock_thing_1, mock_thing_2, mock_thing_3]}
before do
subject.thingies = thingies
end
it 'can iterate through all of them' do
available_things = [mock_thing_1, mock_thing_2, mock_thing_3]
block = MockBlock.new
block.should_receive(:call).with(mock_thing_1).ordered
block.should_receive(:call).with(mock_thing_2).ordered
block.should_receive(:call).with(mock_thing_3).ordered
subject.each(&block)
end
it 'can iterate through all of them, but can exclude one' do
available_things = [mock_thing_1, mock_thing_3]
block = MockBlock.new
block.should_receive(:call).with(mock_thing_1).ordered
block.should_not_receive(:call).with(mock_thing_2)
block.should_receive(:call).with(mock_thing_3).ordered
subject.each(:except => mock_thing_2, &block)
end
end
describe 'when there are no thingies' do
it 'returns an empty array when iterating' do
subject.each { }.should == []
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment