如何在RSpec Controller规范中分配模型实例变量

时间:2010-12-13 13:36:00

标签: ruby-on-rails rspec2

我是RSpec的新手,但我正在尝试为Rails 3应用程序中的一些新功能创建RSpec2控制器规范。我有一个belongs_to:user的模型,我想确保在创建模型的新实例时由我的控制器设置用户。

当前登录的用户应该是在create action中分配给模型的用户。我无法让我的规格工作。这就是我所拥有的

# this was generated by rspec-rails and sets up my mock model
def mock_plan_order(stubs={})
  (@mock_plan_order ||= mock_model(PlanOrder).as_null_object).tap do |plan_order|
    plan_order.stub(stubs) unless stubs.empty?
  end
end

# here's the actual test that's not working
context "user logged in" do
    before(:each) do
      login_user # this logs in and sets @current_user - this is working
    end

    describe "POST create" do
        # the spec that is not working
        it "sets the user id to the logged on user" do
          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 }
          assigns(:plan_order).user.should equal(@current_user)
        end
   end
end

这是规格输出

1) PlanOrdersController user logged in POST create with valid params sets the user id to the logged on user
 Failure/Error: assigns(:plan_order).user.should equal(@current_user)

 expected #<User:58754688> => #<User:0x3808680 @name="User_1">
      got #<PlanOrder:58689360> => #<PlanOrder:0x37f8750 @name="PlanOrder_1010">

任何人都知道我做错了什么?

1 个答案:

答案 0 :(得分:2)

您已创建了plan_order对象,因此不会设置任何用户。要么不要模拟/存根,要添加模拟以确保正在设置用户。