4

我使用 mini_test 进行测试。我有一个如下所示的代码部分。

raise Type_Error, 'First Name must not be empty' if  @person.first_name == nil

如何编写此代码的测试?谢谢...

4

2 回答 2

2

我认为您想要assert_raises,它断言传递给它的块/表达式将在运行时引发异常。

例如,我的一个项目有以下 minitest:

  test 'attempting to create a CreditCard that fails to save to the payment processorshould prevent the record from being saved' do
    assert_equal false, @cc.errors.any?

    failure = "simulated payment processor failure"
    failure.stubs(:success?).returns(false)
    failure.stubs(:credit_card).returns(nil)

    PaymentProcessor::CreditCard.stubs(:create).returns(failure)

    assert_raises(ActiveRecord::RecordNotSaved) { create(:credit_card) }
  end

在我的情况下,这样做是:

  • 从支付处理器 API 创建模拟失败消息
  • 在支付处理器上创建信用卡以返回模拟失败
  • 尝试创建信用卡,模拟支付处理器返回失败状态,并断言我的内部保存/创建方法在这些情况下抛出错误

我应该说这个测试代码包括除了 minitest 之外的东西,比如 FactoryGirl,以及(我认为)should 和 mocha 匹配器。换句话说,上面显示的并不是严格的 minitest 代码。

于 2013-04-12T14:43:13.033 回答
1
raise Type_Error, 'First Name must not be empty' if  @person.first_name == nil

为了测试上面的行,我写了一个如下所示的测试。我为此使用了 minitest::spec。

def test_first_name_wont_be_nil
    person.name = nil
    exception = proc{ Context.new(person).call }.must_raise(TypeError)
    exception.message.must_equal 'First Name must not be empty'
end

上下文是进行某些过程的地方。

于 2013-04-15T14:37:48.803 回答