-
-
Save Peeja/1428875 to your computer and use it in GitHub Desktop.
Test a block in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
I actually like that a lot, thanks.