gpt4 book ai didi

ruby-on-rails - RSpec "count"change.by?

转载 作者:行者123 更新时间:2023-12-03 16:29:46 31 4
gpt4 key购买 nike

所以我在看:https://rubyplus.com/articles/1491-Basic-TDD-in-Rails-Writing-Validation-Tests-for-the-Model

只是看到测试技术,我看到了这个:

require 'rails_helper'

describe Article, type: :model do
it 'is valid if title and description fields have value' do
expect do
article = Article.new(title: 'test', description: 'test')
article.save
end.to change{Article.count}.by(1)
end
end

特别是最后一行: end.to change{Article.count}.by(1) .来自阅读 https://relishapp.com/rspec/rspec-expectations/v/3-7/docs/built-in-matchers/change-matcher

它具体说:

The change matcher is used to specify that a block of code changes some mutable state. You can specify what will change using either of two forms:



这是有道理的。但是正在测试 Article.count在实际上没有“做”任何事情的代码块中( article.save 实际改变了 Article.count 那么这究竟是如何工作的?测试是否在运行之前查看代码块中的内容并“预运行”它...比较 .by(1) 之后?

谢谢

最佳答案

有两个代码块正在执行。传递给 expect 的代码块,以及传递给 change 的代码块.这是真正发生的事情,在伪代码中。

difference = 1
initial_count = Article.count

article = Article.new(title: 'test', description: 'test')
article.save

final_count = Article.count

expect(final_count - initial_count).to eq(difference)

我会将您的测试重构为更容易遵循,如下所示:
require 'rails_helper'

describe Article, type: :model do
let(:create_article) { Article.create(title: 'test', description: 'test') }

it 'is valid if title and description fields have value' do
expect { create_article }.to change { Article.count }.by(1)
end
end

关于ruby-on-rails - RSpec "count"change.by?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50630315/

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