Skip to content

Instantly share code, notes, and snippets.

@myronmarston
Created July 31, 2010 17:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save myronmarston/502409 to your computer and use it in GitHub Desktop.
Save myronmarston/502409 to your computer and use it in GitHub Desktop.
def self.define_shared_group_method(new_name, report_label=nil)
report_label = "it should behave like" unless report_label
module_eval(<<-END_RUBY, __FILE__, __LINE__)
def self.#{new_name}(name, &customization_block)
shared_block = world.shared_example_groups[name]
raise "Could not find shared example group named \#{name.inspect}" unless shared_block
providings = extract_providings(customization_block)
describe "#{report_label} \#{name}" do
# setup instance and class helper methods with this value...
providings.each do |key, value|
define_method(key); { value }; end
class << self; define_method(key); { value }; end; end
end
module_eval &shared_block
# run the customization block last so that it can override helper methods.
module_eval &customization_block if customization_block
end
end
END_RUBY
end
# Note: any other class-level DSL methods that you want to be available
# before the shared block runs can be extracted here in a similar fashion.
# We could also extract the class helper method definitions using method missing
# here so they can be evaluated first.
def self.extract_providings(customization_block)
class = Class.new do
@providings = {}
def self.providings; @providings; end
def self.providing(key, value); @providings[key] = value; end
# swallow any other missing class methods...
def self.method_missing(*a); end
class_eval(&customization_block)
end
class.providings
end
shared_examples_for "a measurable object" do
it "should return #{measurement} from ##{measurement_method}" do
subject.send(measurement_method).should == measurement
end
end
describe Array do
it_should_behave_like "a measurable object" do
subject { [2, 13] }
providing :measurement, 2
providing :measurement_method, :size
end
end
describe String do
it_should_behave_like "a measurable object" do
subject { "FooBar" }
providing :measurement, 6
providing :measurement_method, :length
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment