繁体   English   中英

更新动作 rspec

[英]Update action rspec

这是controller

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

它不会进入其他部分。

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

好吧,每次运行此脚本时,数据库都会被截断或删除(取决于您的 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
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM