【问题标题】:Update action rspec更新操作 rspec
【发布时间】:2021-02-03 12:03:52
【问题描述】:

这是控制器

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

private
def line_item_params
      params.require(:line_item).permit(:product_id, :cart_id) #Check this
    end

我编写的测试用例是为了失败而呈现编辑

    context "with invalid parameters" do
      it "renders a successful response (i.e. to display the 'edit' template)" do
        order = create(:order, user_id: user.id, email: user.email)

        category = create(:category)
        product = create(:product, category_id: category.id)
        cart = create(:cart)

        line_item = create(:line_item,order_id: order.id,product_id: product.id,cart_id:cart.id)
        line_item.product_id = 1
        patch line_item_url(line_item), params: { line_item: { product_id:line_item.product_id}}
        expect(response).to render_template(:edit)

      end
    end

我收到以下错误:

     Failure/Error: if @line_item.update(line_item_params)
     
     ActiveRecord::InvalidForeignKey:
       PG::ForeignKeyViolation: ERROR:  insert or update on table "line_items" violates foreign key constraint "fk_rails_11e15d5c6b"
       DETAIL:  Key (product_id)=(1) is not present in table "products".

它不会进入 else 部分。

我无法检查无效参数。请告诉我 谢谢

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 rspec rspec-rails rspec3


    【解决方案1】:

    好吧,每次运行此脚本时,数据库都会被截断或删除(取决于您的 gem 环境),这意味着表的 PK(主键)每次都会增加 ++。所以line_item.product_id = 1 完全无效,因为在测试规范的第一次运行期间可能有 1 个 ID 可用。

    改成动态赋值,你就可以摆脱这个错误了。

    ...
    other_product = create(:product, category_id: category.id)
    
    line_item = create(:line_item, order_id: order.id, product_id: product.id, cart_id: cart.id)
    line_item.product_id = other_product.id # or any other id, that you are creating during this spec, but not just simple integer
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-20
      • 2014-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多