【问题标题】:How to test chain call in RSPEC?如何在 RSPEC 中测试链调用?
【发布时间】:2020-03-05 11:39:14
【问题描述】:

我的电话看起来像

1) foo1 => MyModel.where(id: my_model_ids)
2) foo2 => MyModel.where('date > :new_date', {new_date: DateTime.new(0)})
3) foo2.sum(:count)

如何测试这个调用链? 我试过这个

where_mock = instance_double(ActiveRecord::Relation)
result_mock = instance_double(ActiveRecord::Relation)

filter = 'date > :new_date'
new_data_hash = {new_date: DateTime.new(0)}


expect(where_mock).to receive(:where).with(filter, new_data_hash).and_return(result_mock)
expect(result_mock).to receive(:sum)

但是没用

【问题讨论】:

  • 为什么要模拟这些方法调用而不是仅仅测试结果是否正确?

标签: ruby-on-rails ruby rspec


【解决方案1】:

我想你正在寻找receive_message_chainhttps://relishapp.com/rspec/rspec-mocks/docs/working-with-legacy-code/message-chains

他们给出的例子是:

allow(Article).to receive_message_chain("recent.published") { [Article.new] }

值得注意的是,使用这种方法通常是代码异味的症状。

如果您在此处测试接收到的是消息而不是输出,则可以单独测试第一个方法调用,存根结果,然后测试存根接收到第二个方法调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-26
    • 2011-10-27
    • 2023-02-10
    相关资源
    最近更新 更多