1

I am trying to figure out the way to properly implement tests (RSpec) for a method structured in the following way:

def foo(id)
  url = "xxx#{id}"
  ean = bar(url)
  baz(ean)
end

bar(url) and baz(ean) are both resource-intensive, so my idea was to first test foo(id), and then to test bar(url) and baz(ean) only if foo(id) fails.

it '...' do
  caracteristics = foo(123)
  expected_caracteristics = { a: 1, b: 2, c: 3 }

  expect(caracteristics).to be_truthy
  expect(caracteristics.size).to be >= 1
  expect(caracteristics).to eq(expected_caracteristics)
end

# I want to run the following tests only if the previous one fails

it '...' do
  ean = bar('test.com')

  expect(ean).to include("XXX")
end

it '...' do
  caracteristics = baz(ean)
  expected_caracteristics = { a: 1, b: 2, c: 3 }

  expect(caracteristics).to be_truthy
  expect(caracteristics.size).to be >= 1
  expect(caracteristics).to eq(expected_caracteristics)
end

Not only am I not sure about how to run a test only if another one fails, but I am also not sure whether this is the correct way of "structuring" this test.

benj-p
  • 405
  • 2
  • 10
  • Why test `bar` and `baz` when `foo` fails? When it fails then you have to manually debug and fix it anyway. If it not fails when both methods have been tested and are correct too? – spickermann Jan 30 '22 at 12:32
  • @spickermann thanks for commenting! The reason for which I want to test `bar` and `baz` when `foo` fails is to be able to pinpoint the "root cause" of that failure and to know which of these methods I should focus on fixing (if any). Does that make any sense? – benj-p Jan 30 '22 at 12:48
  • 1
    https://relishapp.com/rspec/rspec-core/v/3-8/docs/filtering/conditional-filters this might help you – stolarz Jan 30 '22 at 12:53
  • What do you think about using a custom matcher with builtin rspec matches? Take a look at this response: https://stackoverflow.com/a/49951024/10527012 – Pedro Paiva Jan 30 '22 at 13:50
  • @stolarz thanks for that, looks really promising. I'm struggling to pass a variable from one "describe" to another right now but once I get that working it should be fine :) – benj-p Jan 30 '22 at 14:23
  • @benj-p From my point of view, you should always be testing both bar and baz and your tests for foo should not depend on those two methods. However, to write the answer I need to know where are those methods defined and whether they are private or not. – BroiSatse Jan 30 '22 at 15:54

0 Answers0