gpt4 book ai didi

ruby-on-rails - rspec Controller 测试 : "expected #count to have changed by -1, but was changed by 0"

转载 作者:行者123 更新时间:2023-11-28 20:17:51 27 4
gpt4 key购买 nike

我无法解决这个错误。我不确定 controller_spec 的哪一部分写错了。请帮忙!

路线

Rails.application.routes.draw do
resources :cases, only: [:index, :show, :new, :create, :edit, :update] do
resources :links, only: [:create, :destroy]
end
end

Controller

class LinksController < ApplicationController

before_action :prepare_case

def destroy
@link = @case_file.links.find(params[:id])
@link.destroy
redirect_to case_path(@case_file)
end

private

def prepare_case
@case_file = CaseFile.find(params[:case_id])
end
end

规范/工厂

FactoryGirl.define do

factory :link do

case_file
url 'www.google.com'

trait :invalid do
case_file nil
url ''
end
end
end

规范/ Controller

require 'rails_helper'

RSpec.describe LinksController, type: :controller do

let(:user) { build(:user) }
before { login_user user }
#for user log in

let(:case_file) { create(:case_file) }
let(:link) { create(:link, case_file: case_file) }

describe "DELETE destroy" do
it "deletes a link" do
expect { delete :destroy, id: link.id , case_id: case_file }.
to change(Link, :count).by(-1)
expect(response).to redirect_to(case_path(case_file))
end
end
end

错误信息

$rspec 规范/controllers/links_controller_spec.rb...F

失败:

1) LinksController DELETE destroy 删除一个链接 失败/错误: expect { delete :destroy, id: link.id , case_id: case_file }。 改变(Link, :count).by(-1)

预期 #count 已更改为 -1,但已更改为 0 # ./spec/controllers/links_controller_spec.rb:28:in `block (3 levels) in '

在 1.18 秒内完成(文件加载时间为 5.03 秒)4个例子,1个失败

失败的例子:

rspec ./spec/controllers/links_controller_spec.rb:27 # LinksController DELETE destroy 删除链接

最佳答案

这是一个典型的错误(虽然我找不到很好的重复)。当您使用 let 时,rspec 仅执行关联的 block ,在您的情况下创建 Link 对象,当您第一次引用它时。

因此,链接在传递给 expect 的 block 中同时创建和销毁:计数不变,测试失败。

您需要做的就是在测试的前面引用link。如果您使用 let! 而不是 let,那么 rspec 将在测试之前创建对象,而不是仅仅在测试中的某处添加对 link 的随机调用该示例运行并且您的测试通过。这和做的一样

before(:example) { link }

关于ruby-on-rails - rspec Controller 测试 : "expected #count to have changed by -1, but was changed by 0",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36820945/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com