[rspec-users] Shared Helpers

Nicolás Sanguinetti godfoca at gmail.com
Tue Feb 23 13:49:54 EST 2010


On Tue, Feb 23, 2010 at 3:41 PM, Matt Wynne <matt at mattwynne.net> wrote:
>
> On 23 Feb 2010, at 17:30, Scott Taylor wrote:
>
>>
>> Has there been any development on shared helpers / it_should_behave_like
>> feature in rspec?
>>
>> I forget the reasons, but I remember a patch for something like this was
>> rejected:
>>
>>   it_should_behave_like "an_entry", :locals => { :entry => Entry.new }
>>
>> OR:
>>
>>   before do
>>     @entry = Entry.new
>>   end
>>
>>   it_should_behave_like "an_entry", :locals => lambda {
>>     {
>>       :entry => @entry
>>     }
>>   }
>>
>> Is there any code which now deals with the variable passing issue in
>> rspec?
>>
>> Best,
>>
>> Scott
>
> FWIW, what I've done in this situation is expect that the ExampleGroup I've
> mixed the shared behaviour into to define a method, and call that from the
> shared examples - if it's not defined you'll find out pretty quickly.
> Another approach is to just expect the @variable to be set:
>
>  describe "an entry" do
>    before
>      @entry or raise("You need to set @entry to use this shared example
> group")
>    end
>  end
>
> It's not great, but it makes the shared example group a little more
> self-documenting than if you just shared the instance variable without the
> check.
>
> cheers,
> Matt

We do what Matt does, plus we document on top of the shared examples
the interface the example group needs:

# You need to provide an <invalid_record> method that returns a record without
# saving, in an invalid state, for this mixin to work.
shared_examples_for "a model that can disable validations" do
  context "when checking for a record's validity" do
    it "always returns true if you disabled validations" do
      described_class.disable_validations!
      invalid_record.should be_valid
    end

    it "falls back to the usual behavior if you enable validations" do
      described_class.enable_validations!
      invalid_record.should_not be_valid
    end
  end

  ...
end

describe User do
  let :invalid_record do
    User.make_unsaved(:invalid)
  end

  it_should_behave_like "a model that can disable validations"
end


Cheers,
-foca

> http://mattwynne.net
> +447974 430184
>
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users
>


More information about the rspec-users mailing list