1

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

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

# 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">

有人知道我在做什么错吗?

4

1 回答 1

2

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

于 2010-12-13T13:55:16.957 回答