4

I use mini_test for testing. I have a code part like below.

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

How can I write this code's test? Thanks...

miyamotomusashi
  • 531
  • 7
  • 22

2 Answers2

2

I think you want assert_raises, which asserts that the block/expression passed to it will raise an exception when run.

For example, one of my projects has the following 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

What this does, in my case, is:

  • Create a simulated failure message from the payment processor API
  • Stub the creation of a credit card on the payment processor to return the simulated failure
  • Try to create a credit card, simulating that the payment processor has returned a failed status, and assert that my internal save/create method throws an error under these conditions

I should say that this test code includes things in addition to minitest, such as FactoryGirl, and (I think) shoulda and mocha matchers. In other words, what is shown above isn't strictly minitest code.

jefflunt
  • 33,527
  • 7
  • 88
  • 126
1
raise Type_Error, 'First Name must not be empty' if  @person.first_name == nil

For testing above line, I wrote a test like below. I used minitest::spec for this.

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

Context is place where make some process.

miyamotomusashi
  • 531
  • 7
  • 22