简体   繁体   中英

In rails, what is the best way to define constant strings (like error messages, notices, etc)?

I've been learning rails for the last week or so and I'm just starting to get into BDD. A typical example in any cucumber or rspec tutorial is to ensure a success/error message is displayed as a check that an action succeeded or failed.

This means there is now a constant message, such as "Your message is delivered successfully" twice in the code - one in the application and another in the tests. This is strange to me... it isn't DRY, which rails developers live by, and if you wanted to change the message to something else, you have to do it twice.

Is this standard? I've read about en.yml in the locales directory and was wondering if anyone used it for their strings. I haven't seen this in any tutorials so far which is why I'm asking. Are the strings in en.yml visible to cucumber/rspec tests? If so, how do I access them in code? If en.yml isn't the way to go, how do rails developers store their constant string values?

Use locale files to store locale dependent strings like the messages you are mentioning. Then just do something like:

page.should have_content I18n.translate(:message_delivered)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM