【问题标题】:Expected Exception but nothing was raised using Rspec. Trying to raise_error when variable is empty预期异常,但使用 Rspec 未引发任何异常。当变量为空时尝试引发错误
【发布时间】:2021-05-08 04:29:31
【问题描述】:

我正在尝试通过最后一个测试,尝试引发一个我无法使其工作的异常。有什么我没看到的吗?我已经查看了几个小时并寻找答案,提前感谢任何可能对此做出回应的人。

错误信息:

失败/错误:期望{birthday_list.show_birthdays}.to raise_error{'没有可用的生日!'} 预期异常,但未引发任何异常

测试:



describe BirthdayList do
birthdays = @birthdays
birthday_list = BirthdayList.new


describe '#add' do
  it 'adds a birthday to the list' do
    expect(birthday_list.add('name','date')).to eq   ([{:dates=>"date", :names=>"name"}])
  end
end

describe '#show_birthdays' do
  it 'throws an error when there is no birthdays' do
  @birthdays = []
    expect{birthday_list.show_birthdays}.to raise_error{'No birthdays avalible!'}
  end

  it 'prints all birthdays' do


    expect(birthday_list.show_birthdays).to eq "name, date\n"
  end
end

end

和代码


class BirthdayList
  def initialize
    @birthdays = []
  end

  def add name,date
    birthday = {:names => name, :dates => date }
    @birthdays.push(birthday)
  end

 def show_birthdays
   raise 'No birthdays avalible!' unless @birthdays
   
   list_to_print = ''

   @birthdays.each do |b|
     print "#{b[:names]}, #{b[:dates]} \n"
   end

   @birthdays.each do |b|
     list_to_print += "#{b[:names]}, #{b[:dates]}\n"
   end

   list_to_print
end

 end

【问题讨论】:

    标签: ruby unit-testing testing rspec


    【解决方案1】:

    您的断言语法看起来不正确。 raise_error 匹配器需要将预期的异常作为参数而不是块传递。

    代替:

      expect { my_code }.to raise_error { 'Oops!' }
    

    你需要使用:

      expect { my_code }.to raise_error('Oops!')
    

    或匹配器的任何替代形式。

    【讨论】:

    • 感谢您的回复!实际上是这条线“提高“没有生日可用!”除非@birthdays' 不起作用。现在我把它改成:if @birthdays == [] raise'No birthdays avalible!'结束
    • 还需要将测试中的@birthdays = [] 更改为 bday_list = BirthdayList.new,然后在测试中使用它而不是birthday_list。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 2015-11-28
    相关资源
    最近更新 更多