gpt4 book ai didi

ruby - 如何测试 rspec 中方法调用的顺序?

转载 作者:数据小太阳 更新时间:2023-10-29 06:41:22 24 4
gpt4 key购买 nike

我有一个类使用命令模式按顺序执行一系列简单的转换步骤。数据以数据馈送(XML 格式)的形式出现,然后使用单一用途的步骤类通过多个步骤进行转换。所以它可能看起来像这样(实际类名不同):

raw_data = Downloader.new(feed)
parsed_data = Parser.new(raw_data)
translated_data = Translator.new(parsed_data)
sifted_data = Sifter.new(translated_data)
collate_data = Collator.new(sifted_data)

等等

我对每个类都有单元测试,我有集成测试来验证整个流程,包括每个类都被调用。

但是我没有办法测试它们被调用的顺序

我想要一些测试,这样我就可以知道:下载器首先被调用,然后是解析器,然后是翻译器,等等。

这是在 Ruby 和 Rspec 3 中。

我确实找到了这个:http://testpractices.blogspot.com/2008/07/ordered-method-testing-with-rspec.html但这是 2008 年的,它也非常难看。有没有更好的方法来测试方法执行顺序?

谢谢!

最佳答案

RSpec Mocks 提供 ordered至少从 RSpec 3.0 开始:

You can use ordered to constrain the order of multiple message expectations. This is not generally recommended because in most situations the order doesn't matter and using ordered would make your spec brittle, but it's occasionally useful. When you use ordered, the example will only pass if the messages are received in the declared order.

请注意,RSpec 同意@spickermann 的观点,即这不是推荐的做法。但是,在某些情况下是必要的,尤其是在处理遗留代码时。

这是 RSpec 的传递示例:

RSpec.describe "Constraining order" do
it "passes when the messages are received in declared order" do
collaborator_1 = double("Collaborator 1")
collaborator_2 = double("Collaborator 2")

expect(collaborator_1).to receive(:step_1).ordered
expect(collaborator_2).to receive(:step_2).ordered
expect(collaborator_1).to receive(:step_3).ordered

collaborator_1.step_1
collaborator_2.step_2
collaborator_1.step_3
end
end

失败的例子:

RSpec.describe "Constraining order" do
it "fails when messages are received out of order on one collaborator" do
collaborator_1 = double("Collaborator 1")

expect(collaborator_1).to receive(:step_1).ordered
expect(collaborator_1).to receive(:step_2).ordered

collaborator_1.step_2
collaborator_1.step_1
end

it "fails when messages are received out of order between collaborators" do
collaborator_1 = double("Collaborator 1")
collaborator_2 = double("Collaborator 2")

expect(collaborator_1).to receive(:step_1).ordered
expect(collaborator_2).to receive(:step_2).ordered

collaborator_2.step_2
collaborator_1.step_1
end
end

关于ruby - 如何测试 rspec 中方法调用的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31762331/

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