7

I'm currently creating an object in subject and need to test if this raises an exception. The following code illustrates what I'm trying to achieve:

describe MyClass do
  describe '#initialize' do
    subject { MyClass.new }

    it { is_expected.not_to raise_error(Some::Error) }
  end
end

I have a feeling I'm going about this the wrong way. What is the preferred way to set the subject to a new object, without creating the object twice?


Update

My problem was two-fold. Firstly, this syntax does not work:

it { is_expected.not_to raise_error }

Using expect inside an it block does, however (as pointed out by Jimmy Cuadra):

it 'does not raise an error' do
  expect { subject }.not_to raise_error
end

I am not well enough acquainted with RSpec to tell you why this is.

Secondly, since RSpec 3.0.0.beta1, it is longer possible to use raise_error with a specific error class. The following, therefore, is invalid:

expect { subject }.to raise_error(Some::Error)

For more information, see

4

2 回答 2

11

如果我理解正确,您正在尝试测试实例化一个类是否会导致异常。你只需这样做:

describe MyClass do
  it "doesn't raise an exception when instantiated" do
    expect { subject }.not_to raise_error
  end
end 
于 2014-07-27T18:10:03.240 回答
6

通过语法做到这一点的正确方法is_expected是用 Proc 包装您的主题值,如下例所示:

describe MyClass do
  describe '#initialize' do
    subject { -> { MyClass.new } }
    it      { is_expected.not_to raise_error(Some::Error) }
  end
end

这种方式更准确,因为有时您的用例是期望不应抛出特定类型的异常(而允许抛出其他异常)。这种方法将涵盖此类用例。

于 2015-09-17T21:59:59.310 回答