On Nov 14, 2011, at 6:57 PM, Patrick J. Collins wrote:

> So, I recognize that there are many different ways to accomplish what I am
> trying to do, but none of them seem to be as elegant as I would like.
> 
> I have a few classes which need to have shared functionality...
> 
> So I could do something like this:
> 
> module NameBuilder
> 
>  def build_name(*args)
>    args.shift.to_s + args.flatten.map {|component| "[#{component}]"}.join
>  end
> 
> end
> 
> class Foo
>  include NameBuilder
> 
>  def initialize(arg1, arg2)
>    ...
>  end
> end
> 
> class Bar
>  include NameBuilder
> 
>  def initialize(arg1, arg2)
>    ...
>  end
> end
> 
> ...
> 
> But, then I need to do something like:
> 
> shared_examples "a nameable thingie" do |obj|
> 
>  describe "#build_name" do
> 
>    it "it adds the collection of arguments to the base components and formats 
> them for a form element name attribute" do
>      obj.build_name(:lol, :lollerskates, :roflcopter).should == 
> "lol[lollerskates][roflcopter]"
>    end
> 
>  end
> 
> end
> 
> describe Foo do
>  it_behaves_like "a nameable thingie", Foo.new(nil, nil)
> end
> 
> describe Bar do
>  it_behaves_like "a nameable thingie", Bar.new(nil, nil)
> end
> 
> Which I don't like, mainly because Foo & Bar's initialize methods require
> arguments, and I am having to do (nil, nil) which seems very uncool...

Use the described class:


shared_examples "a nameable thingie" do |klass|
  describe "#build_name" do
    it "it adds the collection of arguments to the base components and formats 
them for a form element name attribute" do
      described_class.new(nil,nil).build_name(:lol, :lollerskates, 
:roflcopter).should == "lol[lollerskates][roflcopter]"
    end
  end
end

describe Foo do
  it_behaves_like "a nameable thingie"
end

describe Bar do
  it_behaves_like "a nameable thingie"
end

Cheers,
David
_______________________________________________
rspec-users mailing list
rspec-users@rubyforge.org
http://rubyforge.org/mailman/listinfo/rspec-users

Reply via email to