ruby-on-rails - Rails 5 失败测试 ActiveRecord::AssociationTypeMismatch

标签 ruby-on-rails ruby testing activerecord

我目前正在使用使用 Rails 5 进行敏捷开发,但在我的测试中遇到了问题。也就是说,在它期望 Product 但得到 String 的地方发生了关联不匹配。我已尝试修复我的 line_items_controller_test.rb 中从@line_item.product 到@line_item.product_id 的行,但无济于事,我已经尽我所能四处寻找。

这是我的测试文件 line_items_controller_test.rb

  test "should update line_item" do
    patch line_item_url(@line_item), params: { line_item: { cart_id: @line_item.cart_id, product: @line_item.product } }
    assert_redirected_to line_item_url(@line_item)
  end

我的终端测试失败

Error:
LineItemsControllerTest#test_should_update_line_item:
ActiveRecord::AssociationTypeMismatch: Product(#70143083725900) expected, got String(#70143078473840)
    app/controllers/line_items_controller.rb:47:in `block in update'
    app/controllers/line_items_controller.rb:46:in `update'
    test/controllers/line_items_controller_test.rb:40:in `block in <class:LineItemsControllerTest>'


bin/rails test test/controllers/line_items_controller_test.rb:39

这是 Controller 本身,它提到以 respond_to 开头的 47 和 46

  def update
    respond_to do |format|
      if @line_item.update(line_item_params)
        format.html { redirect_to @line_item, notice: 'Line item was successfully updated.' }
        format.json { render :show, status: :ok, location: @line_item }
      else
        format.html { render :edit }
        format.json { render json: @line_item.errors, status: :unprocessable_entity }
      end
    end
  end

如果您需要更多信息,请告诉我。您也可以在 https://github.com/jamesemcc/depot 查看我的 repo 协议(protocol)

最佳答案

好的。不仅你的测试有问题,应用也有问题。

  1. > https://github.com/jamesemcc/depot/blob/master/app/controllers/line_items_controller.rb#L75您应该在此处允许 product_id,而不是 product。您不能从浏览器传递 Product 对象。
  2. 您应该从 View 和测试中传递 product_id

祝你好运!

关于ruby-on-rails - Rails 5 失败测试 ActiveRecord::AssociationTypeMismatch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41135445/

相关文章:

ruby-on-rails - Rails_admin,用另一个字段的值更改一个字段的值

css - Rails 在哪里包含 @media css 标签?

ruby-on-rails - Rails 3 + 为数据库中的不同用户设计 : user_signed_in??

ruby - 不可谷歌搜索的 ruby 方法 method

unit-testing - 当 junit 本身为每个测试重新初始化类时,为什么要使用 @before 进行类变量重新初始化

ruby-on-rails - RSpec 无法在共享示例中使用定义的变量

mysql - 尝试连接到 MySQL 本地主机服务器,但浏览器无法加载并要求我下载文件

ruby-on-rails - 如何通过 html.erb View 中的单选按钮使用 if else 功能?

ruby - 正则表达式捕获 html 标签内的多个项目

testing - 将外部证书添加到 jmeter