[rspec-users] @current_user in controller specs

Elliot Winkler elliot.winkler at gmail.com
Tue Dec 14 13:07:06 EST 2010


You can't say User.new(:id=>27) as ActiveRecord prevents :id from being
mass-assigned like that (in the case of an action that does
User.new(params[:user]) in the controller, people would be able to set the
id through the POST data). Try User.new.tap {|u| u.id = 27 } instead.

-- Elliot

On Fri, Dec 10, 2010 at 3:15 PM, John Gadbois <jgadbois at gmail.com> wrote:

> Hi,
>
> I'm an absolute beginner with RSpec, so I apologize if this question
> doesn't make sense.
>
> I'm using RSpec 2, Rails 3.  I have a @current_user instance variable that
> I can access in my controller.  I have a controller called
> PlanOrderController.  In the create action of this model, I would like to
> assign the user_id of the PlanOrder object to be the user_id of the
> @current_user before saving.
>
> I have the generated rails controller specs so I'm starting with those.
>  Basically I want my controller spec for the create action to test to make
> sure that the newly created PlanOrder has it's user_id property set to @
> current_user.id
>
> The code I have so far is below but it's not working
>
>       it "sets the user id to the logged on user" do
>         @current_user = User.new(:id=>27)
>         controller.stub!(:current_user).and_return(@current_user)
>
>         PlanOrder.stub(:new).with({"days_per_week" => 3,
> "description"=>"Test", "purpose_id"=>1 }) { mock_plan_order(:save => true) }
>         post :create, :plan_order =>{"days_per_week" => 3,
> "description"=>"Test", "purpose_id"=>1 }
>         plan_order = assigns(:plan_order)
>         plan_order.user_id.should be(@current_user.id)
>       end
>
> Any help would be appreciated.
>
> Thanks,
> John
>
> _______________________________________________
> rspec-users mailing list
> rspec-users at rubyforge.org
> http://rubyforge.org/mailman/listinfo/rspec-users
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://rubyforge.org/pipermail/rspec-users/attachments/20101214/4bc610c0/attachment.html>


More information about the rspec-users mailing list