Skip to content

Instantly share code, notes, and snippets.

@valdemarua
Created September 24, 2024 17:12
Show Gist options
  • Save valdemarua/578aae7730c54e167a0630c4be16bb55 to your computer and use it in GitHub Desktop.
Save valdemarua/578aae7730c54e167a0630c4be16bb55 to your computer and use it in GitHub Desktop.
Retry on failure helper
# Usage examples:
#
# 1. Basic usage with default parameters:
#
# retry_on_failure do
# expect(some_condition).to be_true
# end
#
# result = retry_on_failure do
# expect(some_condition).to be_true
# "Operation successful"
# end
# puts result # Output: "Operation successful"
#
# 2. Custom max retries and delay:
# retry_on_failure(max_retries: 5, delay: 5) do
# expect(api_call).to eq(expected_response)
# end
#
# 3. Using with a custom expectation:
# retry_on_failure do
# expect { complex_operation }.to change(SomeModel, :count).by(1)
# end
#
# 4. Handling specific errors:
# parsed_data = retry_on_failure do
# response = make_api_call
# expect(response.status).to eq(200)
# parsed = JSON.parse(response.body)
# expect(parsed).to include("success" => true)
# parsed
# end
# puts parsed_data # Output: Parsed JSON data
def retry_on_failure(max_retries: 3, delay: 10)
retries = 1
begin
yield
rescue RSpec::Expectations::ExpectationNotMetError => e
puts e.message
puts "Retrying.... (Attempt #{retries} of #{max_retries})"
if retries <= max_retries
retries += 1
sleep delay
retry
else
raise e
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment