You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rspec如何校验方法接收参数哈希的键值对子集?

如何让RSpec仅校验方法参数哈希的指定子集

要实现只校验Stripe::Checkout::Session.create参数中line_items的正确性,忽略其他额外键值对,你可以使用RSpec内置的hash_including匹配器,修改后的测试代码如下:

it 'calls Stripe::Checkout::Session#create with the correct line items' do
  expect(Stripe::Checkout::Session).to receive(:create).with(
    hash_including(
      line_items: [{ price: "bla", quantity: 1 }]
    ),
    hash_including(stripe_account: "bla") # 可选:如果需要校验第二个参数的子集
  )
  subject
end

关键说明

  • hash_including的作用是匹配包含指定键值对的任意哈希,无论哈希中是否存在其他未指定的键,都不会触发测试失败。
  • 针对方法的多个参数(比如报错里显示的第二个哈希参数),可以为每个参数单独使用hash_including,按需校验对应参数的子集内容。

内容的提问来源于stack exchange,提问作者David Geismar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 17:36:12