ruby-on-rails - 更新方法的参数数量错误(1 对 2)

标签 ruby-on-rails ruby unit-testing debugging minitest

我在追踪为什么我的更新方法没有获得所需参数时遇到了问题。我对 show 进行了类似的测试,有效载荷正在运行。在这种情况下,有问题的路线是 invoice/invoice_id/trip/id。如果您能帮我找出错误并就今后如何解决此类问题提供任何建议,那就太好了。

这是更新方法。

def update
  if @trip.update(@trip.trip_id, trip_params)
    head :no_content
  else
    render json: [@invoice, @trip].errors, status: :unprocessable_entity
  end
end

使用以下私有(private)方法。

private

  def set_trip
    @trip = Trip.where(:invoice_id => params[:invoice_id], :trip_id => params[:id] )
  end

  def trip_params
    params.require(:trip).permit(:trip_id, :depart_airport, :arrive_airport, :passenger_first_name, :passenger_last_name, :passenger_count, :departure_date, :merchant_id)
  end

  def load_invoice
    @invoice = Invoice.find(params[:invoice_id])
  end

end

我失败的测试看起来像这样。

test "should update trip" do
  put :update, invoice_id: @invoice.invoice_id, id: @trip,
   trip: {arrive_airport: @trip.arrive_airport,
   depart_airport: @trip.depart_airport,
   departure_date: @trip.departure_date,
   passenger_count: @trip.passenger_count,
   passenger_first_name: @trip.passenger_first_name, 
   passenger_last_name: @trip.passenger_last_name}
 assert_response 204
end

最佳答案

如果你在 before_action 中调用 set_trip 那么 update() 方法应该是这样的

def update
  if @trip.update(trip_params)
    head :no_content
  else
    render json: [@invoice, @trip].errors, status: :unprocessable_entity
  end
end

update()是一个可以使用对象调用的实例方法,你只需要将trip_params传进去,希望对你有帮助!

关于ruby-on-rails - 更新方法的参数数量错误(1 对 2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36179621/

相关文章:

ruby-on-rails - Rails Rspec 测试 Controller 已触发 Websockets 事件

ruby - 这段代码中 row[/\w+/] 的用途是什么?

ruby - 模式匹配时 =~ 和 match() 有什么区别?

ruby - 如何使用 Ruby 从服务中获取 Windows 域中的用户名?

java - 如何测试重定向样式API

visual-studio-2010 - 在 Microsoft 单元测试中使用配置文件

ruby-on-rails - Rails - 如何对嵌套记录使用 TRY

ruby-on-rails - 将 Rails CSV 解析为哈希

ruby-on-rails - rails : Field 'browser' doesn't contain a valid alias configuration when pushing to Heroku

unit-testing - 在 Vue 3 组件单元测试中测试 Pinia 的变化