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

Matt Wynne matt at mattwynne.net
Fri Jun 12 04:43:00 EDT 2009

On 12 Jun 2009, at 08:34, Lee wrote:

> In my controller's create method, I have:
> @sub_context = @context.create_sub_context(params[:context][:name])
> If I do not specify params in the "post :create" call in my controller
> spec then I get the following error for each example:
> You have a nil object when you didn't expect it!
> You might have expected an instance of ActiveRecord::Base.
> The error occurred while evaluating nil.[]
> So I see that it is trying to access :name when :context is nil which
> can be avoided if I ensure each post :create includes a params for
> [:context][:name] e.g.
> post :create, :context => {"name" => "Seniors"}
> 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?
> For example, the params are redundant in some examples e.g.
>    it "should save the context" do
>      @context.should_receive(:save)
>      post :create, :context => {"name" => "Seniors"}
>    end
> Thanks.

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.

describe "when the context has a name"
   def do_post(params = {})
     post :create, (:context => {"name" => "Seniors"}).merge(params)

   it "should save the context" do

Make sense?

Matt Wynne

More information about the rspec-users mailing list