Reputation: 82
I have a en.yml
which contains the following
en:
article:
title:
format: "Requires at least one alphanumeric character"
title_format: "Title Requires at least one alphanumeric character"
The article.title.format
is used in my article model and article.title_format
is used in article_test test. Is there any way to make this DRY?
Upvotes: 2
Views: 72
Reputation: 4686
YAML is limited for things like this, but you do have anchors, aliases and merge_keys. This SO answer is VERY exhaustive on this issue.
So, you can repeat the exact same message, but not modify that message without some other library or code injection:
&standard_answer: "Requires at least one alphanumeric character"
en:
article:
title:
format: *standard_answer
title_format: *standard_answer
in Ruby, is equivalent to:
en:
article:
title:
format: "Requires at least one alphanumeric character"
title_format: "Requires at least one alphanumeric character"
If you are trying to test model validations, I think you're doing too much anyway:
What you want to know is: "Can I save this record without any alphanumeric characters in the title?"
I would only test whether the validation succeeds or fails.
If you're using RSpec, I like this pattern.
Or, another option, RSpec Expectations ships with Predicate matchers:
# prove the record is valid
expect(record).to be_valid
# make the record invalid in only 1 way
record.title = 'does not have a number'
expect(record).to be_invalid # also works: expect(record).not_to be_valid
Note that I'm making sure the record is valid first, then changing one thing, then checking for validity again. This helps ensure you are testing the right validation.
Upvotes: 1