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

标签 ruby-on-rails testing rspec rspec-rails

我无法解决这个错误。我不确定 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/

相关文章:

sql - 如何对 where 语句的结果进行排序

mysql - Rails 关联模型聚合的性能改进

ruby-on-rails - Dockerfile cmd 返回 Yarn 完整性错误,但 Docker 运行正常

ruby-on-rails - 如何在 rspec 中运行特定的单个测试?

testing - 如何在 Webdriver Sampler 中的 Jmeter 中使用 java 加载 excel 或 csv 文件

ruby - 如何测试 RSpec 中的信号处理,特别是 SIGTERM 的处理?

ruby-on-rails - Ruby on Rails - ActiveRecord::Relation 计数方法错误?

java - Spring MVC Controller 测试失败 - 未设置内容类型

user-interface - 从 X11 GUI 中提取文本?

ruby-on-rails-3 - 调用 FactoryGirl.create 进行所有 rspec Controller 测试?