【问题标题】:Expect an instance of a specific class as a keyword argument期望特定类的实例作为关键字参数
【发布时间】:2018-11-22 18:47:38
【问题描述】:

我需要允许一个类接收另一个类的实例作为 Rspec/Rspec-mocks 中的参数。

上下文是我正在尝试为 Puppet(即 Ruby 应用程序)创建 Rspec 测试。

我想在 Rspec 中说“类似”-

allow(Puppet::FileServing::Content.indirection).
  to receive(:find).with(
    "puppet:///modules/profile/logstash/logstash.json",
    an_instance # an instance of Puppet::Node::Environment would go  here
).and_return('bar')

创建一个类的假实例似乎不是一种选择,因为接收到的实例取决于运行期间计算的值。

因此,在我的 Pry 调试器中,我看到了:

 =>  99:               Puppet::FileServing::Content.indirection.find(
    100:                 self[:source],
    101:                 :environment => catalog.environment_instance
    102:               )

[1] pry(#<Puppet::Type::Elasticsearch_template>)> catalog.environment_instance
=> <Puppet::Node::Environment:70286646297160 @name="rp_env" @manifest="/Users/alexharvey/git/elk/spec/fixtures/manifests" @modulepath="/Users/alexharvey/git/elk/spec/fixtures/modules" >

我卡住的地方是我不知道如何告诉测试“允许” Puppet::Node::Environment 的实例接收我在调试器中看到的内容。

例如,我不知道字符串“70286646297160”是什么(我猜它以某种方式标识了类的实例?)。

我无法引用这些路径,因为它们特定于我的笔记本电脑,而我正在编写的测试只能在我的笔记本电脑上运行。

那么,我如何“告诉”Rspec“允许”接收我在调试器中看到的这个类实例,假设可以这样做。

(我希望这是有道理的。显然,这有点超出我的 Rspec/Ruby 知识范围。)

【问题讨论】:

  • hash_including(environment: instance_of(Puppet::Node::Environment)) 而不是 an_instance ?
  • 哇,这完全正确。你能回答一下吗?

标签: ruby rspec


【解决方案1】:

您可以将hash_includinginstance_of 匹配器一起使用(而不是在您的示例中写为an_instance):

hash_including(environment: instance_of(Puppet::Node::Environment))

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2014-11-20
  • 2023-02-17
  • 2020-11-06
  • 2017-12-01
  • 2013-05-29
  • 2013-07-12
  • 1970-01-01
  • 2021-11-13
相关资源
最近更新 更多