#96 new
Chad Humphries

[#11707] paramters for shared behaviours

Reported by Chad Humphries | November 19th, 2007 @ 06:02 AM

It would be useful if shared behaviours could accept parameters.

this thread on the rspec users mailing list is a good example of when such a feature is needed:

http://www.nabble.com/dynamic-sp...

Comments and changes to this ticket

  • Chad Humphries

    Chad Humphries December 17th, 2007 @ 12:04 PM

    Date: 2007-06-20 07:35

    Sender: David Chelimsky

    Giving this some more thought, this turns out to be rather

    problematic. Not only due to the re-design work but because of

    usage problems. Let's say you have the following setup:

    describe "All Accounts", :shared => true do
    |account|
      it "should let you withdraw less than it has" do
        account.deposit 50
        account.withdraw 20
        account.balance.should == 30
      end
      it "should not let you withdraw more than it has" do
        account.deposit 20
        account.withdraw 21
        account.balance.should == 20
      end
      ...
    end
    
    describe CheckingAccount do
      it_should_behave_like "All Accounts",
    CheckingAccount.new
      ...
    end
    

    This seems perfectly reasonable, right? Well the first problem

    is that the two examples in the shared behaviour don't have access

    to the account instance. You'd have to do this to your

    implementation:

    describe "All Accounts", :shared => true do |acc|
      def account
        acc
      end
      ...
    end
    

    Once that problem is solved, we would find that the second example

    would fail saying the balance is 29. Why? Because CheckingAccount.new

    would only be evaluated once, and the same instance would be

    used in both of the examples.

    We could solve by passing a block to it_should_behave_like:

    describe CheckingAccount do
      it_should_behave_like "All Accounts"
    {CheckingAccount.new}
      ...
    end
    

    Or passing method names:

    describe CheckingAccount do
      it_should_behave_like "All Accounts",
    :new_checking_account
      
      def new_checking_account
        CheckingAccount.new
      end
      ...
    end
    

    But now we're starting to loose the benefits to verbosity and

    confusion.

    Anybody see a simpler way?

Please Login or create a free account to add a new comment.

You can update this ticket by sending an email to from your email client. (help)

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

Behaviour Driven Development for Ruby.

Shared Ticket Bins

People watching this ticket