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
相关产品推荐
相关产品推荐

