2010-12-13 19 views
1

我是RSpec的新手,但我正在嘗試爲Rails 3應用程序中的某些新功能創建RSpec2控制器規範。我有一個belongs_to:user模型,我想確保用戶在創建我的模型的新實例時由我的控制器進行設置。如何檢查模型實例變量正在RSpec控制器規格中分配

當前登錄的用戶應該是在創建操作中分配給模型的用戶。我無法使我的規格工作。下面是我有

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

任何人都知道我做錯了嗎?

回答

2

您創建了plan_order對象,因此不會設置用戶。要麼不模擬/存根,添加一個模擬,以確保用戶被設置。

相關問題