【问题标题】:How to execute once and expect multiple changes with RSpec?如何使用 RSpec 执行一次并期望进行多次更改?
【发布时间】:2017-03-30 15:12:25
【问题描述】:

如果我想测试一个操作会产生某些副作用,我该如何执行一次操作并使用change rspec 匹配器。示例:

expect { some_method }.to change(Foo, :count).by(1)
expect { some_method }.to change(Bar, :count).by(1)
expect { some_method }.to change(Baz, :count).by(1)

我怎样才能只执行一次 some_method 而不是 3 次?

或者我需要做类似的事情:

foo_count_before = Foo.count
bar_count_before = Bar.count
baz_count_before = Baz.count

some_method

foo_count_after= Foo.count
bar_count_after= Bar.count
baz_count_after= Baz.count

expect(foo_count_after - foo_count_before).to eq 1
expect(bar_count_after - bar_count_before).to eq 1
expect(baz_count_after - baz_count_before).to eq 1

【问题讨论】:

    标签: ruby testing rspec rspec-expectations


    【解决方案1】:

    您可以使用compound expectations 将多个期望连接在一起。在您的示例中,这可能如下所示:

    expect { some_method }
      .to change(Foo, :count).by(1)
      .and change(Bar, :count).by(1)
      .and change(Baz, :count).by(1)
    

    【讨论】:

    • 谢谢。另外,关于该主题的全新文章:robots.thoughtbot.com/…
    • 太棒了!我使代码更清洁。非常感谢?
    猜你喜欢
    • 2018-06-19
    • 2015-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    相关资源
    最近更新 更多