当前位置 : 主页 > 编程语言 > ruby >

ruby – Rspec检查是否在没有调用方法的情况下调用了方法

来源:互联网 收集:自由互联 发布时间:2021-06-23
我对RSpec很新,虽然我已经阅读了很多关于如何检查方法是否已被调用但我无法找到适合我所需案例的解决方案.很抱歉,如果这是重复但无法找到任何内容:S 我有一个实现此功能的对象
我对RSpec很新,虽然我已经阅读了很多关于如何检查方法是否已被调用但我无法找到适合我所需案例的解决方案.很抱歉,如果这是重复但无法找到任何内容:S

我有一个实现此功能的对象

def link
  paths.each do |old,new|
    FileUtils.ln_s old, new
  end
end

基于路径(这是对新旧文件进行哈希配对)完成了几个链接.我的测试看起来像这样:

context "linking files to new ones" do
  it "links a sample to the propper file" do
    @comb.link
    expect(FileUtils).to have_received(:ln_s).with("/example/path/files/old.root",
                                             "example/path/nornmfiles/new.root")
  end
end

因为我想测试至少在它们被调用时必须使用has_received方法,因为一旦使用不同的参数调用ln_s方法,接收的方法就会失败.问题是测试失败,因为这是一个测试,我真的要创建链接,因为文件不存在因此它不能引发异常,因为文件不存在.

如何在不实际调用方法的情况下测试它?

一旦进行不同的呼叫,该呼叫也会失败

it "links a sample with a region subpath to the propper file" do
    expect(FileUtils).to receive(:ln_s).with("/example/path/files/pathsuff/old.root",
                                             "/example/path/normfiles/pathsuff/new.root").at_least(:once)
    @comb.link
  end

它给出了这个错误:

RSpec::Mocks::MockExpectationError: FileUtils received :ln_s with unexpected 
arguments
   expected: ("/example/path/files/pathsuff/old.root", 
 "/example/path/normfiles/pathsuff/new.root")
   got: ("/example/path/files/old.root", 
 "/example/path/normfiles/new.root")

这是可以调用的可能发生的其他调用的其他调用

context "linking files to new ones" do
  it "links a sample to the propper file" do
    allow(FileUtils).to receive(:ln_s)

    @comb.link

    expect(FileUtils).to have_received(:ln_s).with(
      "/example/path/files/old.root",
      "example/path/nornmfiles/new.root",
    ).at_least(:once)
  end
end
网友评论