On Sun, Sep 20, 2009 at 9:38 AM, nruth <nick.rutherf...@gmail.com> wrote: > I've been reading through the Rspec book to see if I missed any > tricks, and the discussion of before block use for context setup in > sec 12.6 struck me as interesting and something I had a knee-jerk > reaction to. > > I think that when you are using nested examples to describe a context > change it is bad practice to allow any example within that group to > run outside of that context. This could happen simply because you > forgot to copy and paste (ouch) the setup code into your expectation. > > before blocks solve this problem, but they are so tightly coupled to > the describe call in this case, why not make them a describe method > parameter? Ideally they would be the block passed to describe, but we > can't do that since the example group is using that already. > > So I would propose something like this sketch: > > describe "a new capacity 10 stack", :context => lambda {...@stack = > Stack.new(:capacity => 10)} do > describe "with 4 pushed ints", :context => lambda { 4.times { @stack > << rand(:int) } } do > it "should allow push and return the new size" do > �...@stack.push(rand(:int)).should == 5 > end > end > end > > And the :context would just be executed as if it were a before block. > > Of course you can arrange your specs so that the before block is > directly after the describe, or similar, but this seems a nice > alternative to me.
The order of the before blocks, relative to the examples, is irrelevant. An example group loads up all of its examples and before and after blocks before anything is run. In other words, these two will have the same effect: describe Thing do before(:each) { @thing = Thing.new } it "does something" do @thing.should do_something end end describe Thing do it "does something" do @thing.should do_something end before(:each) { @thing = Thing.new } end This is not the first time your idea has come up, and I've not included it before because I want to avoid assigning specific meaning to keys in the hash passed to describe(). rspec-2 will be using that hash as part of a plugin API, so the more I can leave available, the better. I'll be posting more about that soon, but first things first - gotta get the book off to the printer :) Cheers, David > > It's a nubile idea though. Thoughts? _______________________________________________ rspec-users mailing list rspec-users@rubyforge.org http://rubyforge.org/mailman/listinfo/rspec-users