...

/

A TestCase Scenario

A TestCase Scenario

Learn another reason to include tests with the help of a test-case scenario.

Third reason for including tests

Let’s imagine a more sophisticated scenario. For example, if the total weight is more than a certain threshold, we might need a different kind of box, or two boxes. Or, we want to add a gift weight once we have two or more tennis balls in the cart.

With limited resources (say, we only have one hour while coding on a train), we can skip the test files and test the method manually with Pry. However, do we agree that sharing our code is better when we have a test that checks that the code works fine, so anyone can run all tests with one command and ensure everything is in place?

We’ll create lib directory and two files, shipment.rb and app.rb, the following way:

Here is the app.rb:

require './lib/shipment'

x = Shipment.total_weight(soccer_ball_count: 3, tennis_ball_count: 2, golf_ball_count: 1)
puts x

lib/shipment.rb has the method we discussed above plus the module wrapper:

module Shipment
  module_function

  def total_weight(options={})
    a = options[:soccer_ball_count] || 0
    b = options[:tennis_ball_count] || 0
    c = options[:golf_ball_count] || 0
    (a * 410) + (b * 58) + (c * 45) + 29
  end
end

Similarly, we could create a class instead of a module, and define the method as def self.totalweight. However, it’s not recommended to create a class without intent to create its instance.

Once you run app.rb, you’ll see the total shipping weight:

$ ruby app.rb
1420

So we’ve split the program into two units:

  • The actual logic in shipment.rb (should be tested)
  • And the entry point in app.rb (untested, and it’s okay)

We’ll create a test for the ...