加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 01:37:05 所属栏目:百科 来源:网络整理
导读:我对RSpec很新,虽然我已经阅读了很多关于如何检查方法是否已被调用但我无法找到适合我所需案例的解决方案.很抱歉,如果这是重复但无法找到任何内容:S 我有一个实现此功能的对象 def link paths.each do |old,new| FileUtils.ln_s old,new endend 基于路径(这
我对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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读