在stpec中接受一个接受块的方法调用

时间:2015-03-16 08:47:18

标签: ruby-on-rails unit-testing rspec

我有一个像这样的lib方法:

  def search(*args, &blk)
    MyGem.search(*args, &blk)
  end

我有另一种方法调用此搜索方法,如下所示:

  def members_of(dept)
    result = {}
    search(:attributes => ["displayname", "employeeID"]) do |entry|
      result[entry.employeeid.first.to_i] = entry.displayname.first.to_s
    end
    result
  end

当我为members_of编写rspec测试时,我正在尝试存根search调用。但是我无法弄清楚如何对块进行存根,因为块实际上是使用了方法中定义的局部变量之一。任何帮助,将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:2)

如果使用rspec-mocks,您可以使用partial test double将方法调用存根到MyGem.search

  

部分测试double是系统中实际对象的扩展   在测试环境中的测试双重行为。这种技术在Ruby中很常见   因为我们经常看到类对象充当方法的全局命名空间。

要使MyGem的部分加倍,并期望调用其search类方法:

expect(MyGem).to receive(:search)

然后,您可以将此双重附加行为添加到check the call arguments,将其设为yield valuesraise an error

# match arguments
expect(MyGem).to receive(:search).with(:attributes => ["displayname", "employeeID"])
# yield value
expect(MyGem).to receive(:search).and_yield(42)
# yield multiple values
expect(MyGem).to receive(:search).and_yield(42).and_yield(987)
# raise an error
expect(MyGem).to receive(:search).and_raise(ArgumentError, "bad request")
# all at once!
expect(MyGem).to receive(:search).with(:attributes => ["displayname", "employeeID"])
    .and_yield(42)
    .and_raise(ArgumentError, "bad request")

根据您的信息(看似不完整:dept参数从未使用过......),这是一个完整的例子:

Entry = Struct.new(:employeeid, :displayname)

class MyGem
  def self.search(*args)
    yield Entry.new([1, 2, 3], ["one", "two", "three"])
  end
end

class Organization
  def search(*args, &blk)
    MyGem.search(*args, &blk)
  end

  def members_of(dept)
    result = {}
    search(:attributes => ["displayname", "employeeID"]) do |entry|
      result[entry.employeeid.first.to_i] = entry.displayname.first.to_s
    end
    result
  rescue
    []
  end
end

RSpec.describe Organization do
  describe "#members_of" do
    it "calls search" do
      organization = Organization.new
      expect(MyGem).to receive(:search).with(:attributes => ["displayname", "employeeID"])
          .and_yield(Entry.new([1337, 100, 2000], ["leet", "one hundred", "two thousand"]))
          .and_yield(Entry.new([123], ["one-two-three"]))
      members = organization.members_of("dept")
      expect(members).to match({
          1337 => "leet",
          123 => "one-two-three"})
    end
    it "returns empty array on search error" do
      organization = Organization.new
      expect(MyGem).to receive(:search).and_raise(ArgumentError)
      expect(organization.members_of("dept")).to eq([])
    end
  end
end

此外,在使用部分双精度时,应启用verify_partial_doubles配置选项以确保不存在不存在的类方法。在spec/spec_helper.rb文件中使用此代码段启用它:

RSpec.configure do |config|
  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end
end