我使用mini_test进行测试。我有一个像下面的代码部分。
raise Type_Error, 'First Name must not be empty' if @person.first_name == nil
如何编写此代码的测试? 感谢...
答案 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
在我的情况下,这样做是:
我应该说这个测试代码除了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
上下文是进行某些过程的地方。