微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

更新操作 rspec

如何解决更新操作 rspec

这是控制器

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 部分。

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

解决方法

好吧,每次运行此脚本时,数据库都会被截断或删除(取决于您的 gem 环境),这意味着表的 PK(主键)每次递增 a_list = [1,2,-3,4,5] inverted = [] for x in a_list: inverted.append(-x) print(inverted) 。所以 ++ 它完全无效,因为在测试规范的第一次运行期间可能有 1 个 ID 可用。

改为动态赋值,你就会摆脱那个错误。

line_item.product_id = 1

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。