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

Lee Lee.Longmore at googlemail.com
Fri Jun 12 03:34:41 EDT 2009

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
      post :create, :context => {"name" => "Seniors"}


More information about the rspec-users mailing list