[rspec-users] Can I set params in before[:each] block?

Randy Harmon rjharmon0316 at yahoo.com
Sat Jun 13 11:42:13 EDT 2009

On 6/12/09 1:43 AM, Matt Wynne wrote back to Lee who said:
>> I am wondering if there is a way to avoid having to specify params in
>> each and every example by adding some code to a before[:each] block?
> There are several ways of doing this. The pattern I tend to us is to
> create a method that does the post, and contains default parameters
> which you can override if you want to.
For contrast, I'll describe the method I prefer.  The purpose of this
approach is to simplify and homogenize the interface of the "do it"
routine. By localizing the params in @instance variables, the raw
do_action() is a) easily called by you or the shared example group, b)
consistently named - the shared example doesn't have to care what action
is being done, and c) overridden with parameters at any level of nested
describe()s as you need.

describe "something" do
  before :each do
     @params = { :default => 'values' }
  sub do_action
     post :create, @params
  it_should_behave_like "some shared example group"
     # shared example calls back to our do_action, by convention
  describe "something else" do
     before do
       @params[:special_for_something_else] = 'setting'
       # other setup

     it "whatever" do
       @params[:special_for_whatever] = 'value'


More information about the rspec-users mailing list