【问题标题】:expected Exception but nothing was raised using Rspec预期异常,但使用 Rspec 未引发任何异常
【发布时间】:2014-08-22 03:40:31
【问题描述】:

我正在尝试通过最后一个测试:尝试引发异常我无法使其工作 我的错误日志:

1) 如果没有任何 RIGHT 匹配,那么 VideoSearch 会发现整个采样器集合失败的抱怨 失败/错误:expect(vs.find_all_by_title(2343)).to raise_error 预期异常,但未引发任何异常

我的代码:

class VideoSearch

  attr_accessor :title, :samplers

  def initialize(params)
    @title = params
    @samplers = []    
  end

  def find_all_by_title(title)
    return [] if title.blank?
    Video.where(title: title).first
  end

  def find_the_whole_collection(title)  
    if find_all_by_title(title)
      sampler = find_all_by_title(title)
      @samplers = [sampler] #add the video as the first sample
    else
      raise Exception
      return false # it's false if there 's not any match!
    end
  end
end

我的规格:

describe 'find then whole collection of samplers ' do
  let(:v1) { v1 = Video.create( title: 2345 ) }
  let(:vs) { VideoSearch.new v1.title }
  let(:sample) { vs.find_all_by_title(v1.title) }

  context 'failing' do
    before :each do
      vs.stub(:find_all_by_title).and_return(nil)
    end

    it ' complains if there is not any RIGHT match ' do
      expect(vs.find_all_by_title(2343)).to raise_error
    end
  end     
end

【问题讨论】:

    标签: ruby rspec


    【解决方案1】:

    您的 before 块正在删除 :find_all_by_title 并返回 nil,因此它不会引发错误。存根基本上意味着“如果调用此方法,则执行此操作”,因此在存根时不会运行所有代码。要使您的代码正常工作,请删除 before_block。此外,在测试未找到的项目时,惯例是通过 id-1,因此您的测试可能如下所示:

    context 'failing' do
      it 'complains if there is not any RIGHT match' do
        expect( vs.find_all_by_title(-1) ).to raise_error
      end
    end
    

    另外,你不应该提出Exception,你至少应该提出StandardError(或者,真的是StandardError的一个子类,它更能描述你在做什么。也许,做一个StandardError 的子类称为 TitleNotFoundError?)。

    另外,您的 find_whole_collection 方法中有冗余代码:

    if find_all_by_title(title)
      sampler = find_all_by_title(title)
    

    可以简写为:

    if sampler = find_all_by_title(title)
    

    如果您在 if 语句中为变量分配 nil 值,它将返回 false,因此您只需调用一次 find_all_by_title

    最后,您的 find_all_by_title 方法返回一个空数组 [] 如果为空,但 nil 如果未找到 - 这可能会产生问题(例如,您的 @samples 实例变量将包含 [[]] 如果没有标题通过)。

    【讨论】:

    • 感谢您为我指明正确的道路。现在我有一个关于存根的问题:“所以当存根时,你的所有代码都不会运行。”这实际上是我的意思是不运行“:find_all_by_title”的代码并将其设为假,这样我就可以进入“其他部分”的 if 语句?但也许不是正确的方法?但当然 ypu 也可以像你做的那样添加一个虚假的价值?
    • 我的测试没有通过?
    • 那你为什么打电话给vs.find_all_by_title?您应该调用find_the_whole_collection,然后调用存根find_all_by_title。但是您的测试都是存根,然后调用存根方法,期望它返回与存根返回的内容不同的内容。
    • 阅读你的测试。你存根find_all_by_title 并返回nil,然后你的测试是expect find_all_by_title to raise an error
    • 我遇到了预期错误的问题,因为expect 需要一个块。试试expect { ...code()...}.to raise_error 也许它会起作用,但我不知道为什么我必须在我的规范中这样做。
    猜你喜欢
    • 2021-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    • 2011-11-14
    • 2023-02-12
    • 2012-10-10
    相关资源
    最近更新 更多