Created
December 1, 2011 01:30
-
-
Save coffeencoke/1412587 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
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] | |
subject.each do |thing| | |
result = available_things.delete(thing) | |
result.should_not be_nil | |
end | |
available_things.should be_empty | |
end | |
it 'can iterate through all of them, but can exclude one' do | |
available_things = [mock_thing_1, mock_thing_3] | |
subject.each(:except => mock_thing_2) do |thing| | |
result = available_things.delete(thing) | |
result.should_not be_nil | |
thing.should_not == mock_thing_2 | |
end | |
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
Does anyone have a better way to test or implement this? It's hard to see what I am testing this way, I like readable, self documenting tests.