Skip to content

Instantly share code, notes, and snippets.

@coffeencoke
Created December 1, 2011 01:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save coffeencoke/1412587 to your computer and use it in GitHub Desktop.
Save coffeencoke/1412587 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
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
@coffeencoke
Copy link
Author

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.

@Peeja
Copy link

Peeja commented Dec 4, 2011

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment