Rspec在控制器中更新失败

时间:2011-10-21 18:04:45

标签: ruby-on-rails ruby-on-rails-3.1 rspec2

以下是客户控制器中更新的rspec错误:

 5) CustomersController GET customer page 'update' should be successful
     Failure/Error: put 'update', id => 1, :customer => {:name => 'name changed'}
       <Customer(id: integer, name: string, short_name: string, contact: string, address: string, country: string, phone: string, fax: string, email: string, cell:
string, sales_id: integer, test_eng_id: integer, safety_eng_id: integer, web: string, category1_id: integer, category2_id: integer, active: boolean, biz_status: str
ing, input_by_id: integer, quality_system: string, employee_num: string, revenue: string, note: text, user_id: integer, created_at: datetime, updated_at: datetime)
(class)> received :find with unexpected arguments
         expected: (1)
              got: ("1")
     # ./app/controllers/customers_controller.rb:44:in `update'
     # ./spec/controllers/customers_controller_spec.rb:41:in `block (3 levels) in <top (required)>'

这是rspec代码:

it "'update' should be successful" do

  customer = mock_model(Customer) 
  Customer.should_receive(:find).with(1).and_return(customer)
  customer.stub(:update_attributes).and_return(true)    
  put 'update', :id => 1, :customer => {:name => 'name changed'}
  response.status.should == 302 #redirect()
end

以下是控制器中的更新:

  def update
    @customer = Customer.find(params[:id])
    if @customer.update_attributes(params[:customer], :as => :roles_new_update)
      if @customer.changed
        @message = 'The following info have been changed\n' + @customer.changes.to_s
        @subject ='Customer info was changed BY' + session[:user_name]
        notify_all_in_sales_eng(@message,@subject)
      end  

      redirect_to session[('page'+session[:page_step].to_s).to_sym], :notice => 'Customer was updated successfaully!'
    else
      render 'edit', :notice => 'Customer was not updated!'
    end
  end

有什么想法?感谢。

2 个答案:

答案 0 :(得分:4)

发布的值(通过params哈希访问)是字符串。更正测试的最简单方法是Customer.should_receive(:find).with("1").and_return(customer)

请注意,我们现在将“1”(即字符串)作为预期参数而不是1(一个FixNum)。

答案 1 :(得分:1)

所有参数都以字符串形式传递,我相信find方法正在对一个整数进行隐式对话。要么在控制器中使用to_i使其明确,要么更改规范以期望字符串“1”。