【问题标题】:Expect errors AND other status in Rspec预期 Rspec 中的错误和其他状态
【发布时间】:2018-03-13 09:59:16
【问题描述】:

在 Rspec 测试中,我希望出现错误。但是,我也希望代码在遇到该错误之前会进行(或不进行)一些更改。

我有这样的事情:

it 'raises a VeryBad::NotCool error' do
  expect { instance.err! }.to raise_error(VeryBad::NotCool)
end

这通过了。但是,当我这样做时:

it 'changes the instance status' do
  expect{ instance.err! }.to change{ instance.name }
    .from('nice instance').to('erroring instamce')
end

这失败了,因为

Failure/Error: raise VeryBad::NotCool

失败是有道理的。 但是,另一方面,我认为能够在我们遇到错误之前检查是否发生了更改也很有用,因为代码可能类似于:

def err!
  instance.name = 'erroring instance'
  raise VeryBad::NotCool if instance.save!
end

即使在测试期间出现(预期的)错误,我如何才能检查更改是否发生?

【问题讨论】:

    标签: ruby-on-rails ruby testing rspec


    【解决方案1】:
    it 'raises a VeryBad::NotCool error' do
      expect(instance.name).to eq 'old_value'
      expect { instance.err! }.to raise_error(VeryBad::NotCool)
      expect(instance.reload.name).to eq 'erroring instance'
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-13
      • 2015-09-22
      • 1970-01-01
      • 2022-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多