Skip to content

Commit

Permalink
Notes/tech/coding/rails.md
Browse files Browse the repository at this point in the history
  • Loading branch information
dvogt23 committed Oct 24, 2023
1 parent ee0cbf7 commit b51aa49
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions Notes/tech/coding/rails.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,49 @@ expect(items).to match_array([
```
Source: [benpickles](https://www.benpickles.com/articles/73-testing-an-array-of-objects-with-rspec-have_attributes)

### Custom matcher

```ruby
RSpec::Matchers.define :have_errors_on do |attribute|
chain :with_message do |message|
@message = message
end

match do |model|
model.valid?

@has_errors = model.errors.key?(attribute)

if @message
@has_errors && model.errors[attribute].include?(@message)
else
@has_errors
end
end

failure_message_for_should do |model|
if @message
"Validation errors #{model.errors[attribute].inspect} should include #{@message.inspect}"
else
"#{model.class} should have errors on attribute #{attribute.inspect}"
end
end

failure_message_for_should_not do |model|
"#{model.class} should not have an error on attribute #{attribute.inspect}"
end
end


# usage
describe User do
before { subject.email = "foobar" }

it { should have_errors_on(:email).with_message("Email has an invalid format") }

end
```

## Data class

Similiar to the [value-alike objects](https://docs.ruby-lang.org/en/master/Data.html) in ruby(3.2), here an example for rails:
Expand Down

0 comments on commit b51aa49

Please sign in to comment.