minitest上的错误消息测试

时间:2013-04-12 14:33:22

标签: ruby-on-rails ruby minitest

我使用mini_test进行测试。我有一个像下面的代码部分。

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

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

2 个答案:

答案 0 :(得分:2)

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

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

  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和(我认为)shoulda和mocha匹配器。换句话说,上面显示的并不是严格意义上最小的代码。

答案 1 :(得分: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

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