S
S
Sergey Blokhin2018-09-21 22:00:29
ruby
Sergey Blokhin, 2018-09-21 22:00:29

How to write a test that covers 100% of the code when double checking the condition?

There is some code in which there is a double check of one of the conditions.
How can you write a unit test so that it covers 100% of the code?
A double check is needed if, for some reason, the database returns a result where price is equal to zero.
As an option, write a stub (mock / stub) for the method of working with the database, which would return the product with a zero price?
Or is there another (better) solution?

def products
  # first check on zero price
  products = database.query 'SELECT * FROM product WHERE price > 0;'
  products.map do |product|

    # second check on zero price
    unless product[:price] > 0
      warn 'wrong price'
      next
    end

    # some operation under product
  end
end

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavlo Ponomarenko, 2018-09-22
@TITnet

The correct approach in this case is to separate the receipt of data from the database and the check for a zero price. Well, the simplest example is to create a function ensure_that_every_goods_has_price(goods) and call it instead of including a loop in the body.
Then you will be able to pass a set of goods into it in tests, among which there will be a zero price and thus cover it, and also reuse it if necessary. I don't write in ruby, but the pseudocode is something like this:

def ensure_that_every_goods_has_price(products)
  products.map do |product|
    unless product[:price] > 0
      warn 'wrong price'
      next
    end
  end
end

def products
  products = database.query 'SELECT * FROM product WHERE price > 0;'
  ensure_that_every_goods_has_price(products)
end

## test:

products = database.query 'SELECT * FROM product WHERE price >= 0;'
should_warn ensure_that_every_goods_has_price(products)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question