[Rspec-devel] context could yield an object, and be nested

itsme213 itsme213 at hotmail.com
Sun May 28 12:12:14 EDT 2006


This reflects my quite-incomplete understanding of rspec, please excuse if 
entirely off-base :(

Context sets up the state for several Specify blocks, each of which has many 
Shoulds.

Setup has the executable code to establish context state. It is executed 
once prior to each Specify. (TearDown is its complement).

There is currently no way to relate a Context to other Contexts.

However, it is often natural to think of a Context as related to other 
Contexts in a tree structure, where the parent represents some form of a 
pre-requisite context (e.g. when contexts represent states in some state 
sequence, then parent might be an earlier state; or when contexts represent 
an object in an object graph, then parent might be a container object).

Proposal: Allow contexts to be nested. Setup can either establish the 
context as a side-effect (as it currently does), or return it as an object, 
or both. The block of a nested Context is passed the object returned by the 
parent Context's Setup. The block of each Specify, Setup, and TearDown is 
similarly passed the object returned by the parent Context's Setup.

context :A do
  setup do
    1
  end
  specify :s1 do |c|
    puts c #=> 1
  end
  context :A1 do |c|
    puts c #=> 1
    setup do |c|
      puts c #=> 1
      2
    end
    specify :s2 do |c|
      puts c #=> 2
    end
  end
end

Note: once Specify and Context takes a parent context argument, it might 
make sense for the description string for the Specify to somehow have access 
to that context object.

Setup for a Context is still executed once prior to each Specify for that 
Context. This should probably apply transitively to all parent's Setup.

That said, it would be useful to have Context#start_once (and #end_once) 
methods whose blocks are guaranteed executed exactly once before the first 
Specify & Setup & nested Context (after the last Specify & nested Context & 
TearDown, respectively) in that Context.



More information about the Rspec-devel mailing list