Instructions
Create a custom exception class ValidationError that inherits
from StandardError.
Then create a function validate_age that:
- Returns the age if between 0 and 150
- Raises ValidationError with a message otherwise
Define custom exceptions:
```ruby
class MyError < StandardError; end
raise MyError, "something went wrong"
```
Hints:
- class ValidationError < StandardError; end
- raise ValidationError, 'message'
- Check age range with conditionals
Your Code
class ValidationError < StandardError; end def validate_age(age) raise ValidationError, "Age must be between 0 and 150" unless (0..150).include?(age) age end
RSpec.describe "validate_age" do
it "returns valid ages" do
expect(validate_age(25)).to eq(25)
expect(validate_age(0)).to eq(0)
expect(validate_age(150)).to eq(150)
end
it "raises ValidationError for negative" do
expect { validate_age(-1) }.to raise_error(ValidationError)
end
it "raises ValidationError for too high" do
expect { validate_age(151) }.to raise_error(ValidationError)
end
it "ValidationError inherits from StandardError" do
expect(ValidationError.superclass).to eq(StandardError)
end
end
Results
Click "Run Tests" to see results