我很高兴在控制器中设置flash消息,如下所示:
redirect_to root_path, error: 'This is a highly eloquent and specialised error message just for you, my iridescent, transcendent and all round marvellous bundle of joy! You are not allowed in here you cheeky chappy, you!'
然而,我发现在编写功能规范以测试这些消息正在呈现时,我正在进行大量的复制粘贴:
context 'when user has eaten all the pies' do
let(:cheeky) { FactoryGirl.build(:cheeky_user) }
subject { page }
before do
log_in cheeky
click_link 'steal pies'
end
it_should_behave_like 'home page'
it{ should have_selector('.error', text: 'This is a highly eloquent and specialised error message just for you, my iridescent, transcendent and all round marvellous bundle of joy! You are not allowed in here you cheeky chappy, you!') }
end
当一个断言因为我缺少一个字符而失败时会很痛苦,但更多的是,当得到一堆失败的规范时,因为我已经调整了一些错误消息。
测试错误消息这可能是一个脆弱的规范的例子,但我想测试正在显示的错误消息。
我真的希望能够做到这一点:
#somewhere in rails
ERROR_MSG_23 = 'This is a highly eloquent and specialised error message just for you, my iridescent, transcendent and all round marvellous bundle of joy! You are not allowed in here you cheeky chappy, you!'
#controller
redirect_to root_path, error: ERROR_MSG_23
#spec
context 'when user has eaten all the pies' do
let(:cheeky) { FactoryGirl.build(:cheeky_user) }
subject { page }
before do
log_in cheeky
click_link 'steal pies'
end
it_should_behave_like 'home page'
it{ should have_selector('.error', text: ERROR_MSG_23 ) }
end
这有宝石吗?或者这可以在vanilla rails中实现吗?
答案 0 :(得分:2)
您可以使用I18n
,如下所示:
en.yml:
en:
flash_messages:
message_1: 'This is a highly eloquent and specialised error message just for you, my iridescent, transcendent and all round marvellous bundle of joy! You are not allowed in here you cheeky chappy, you!'
控制器:
redirect_to root_path, error: t('flash_messages.message_1')
规格:
it{ should have_selector('.error', text: I18n.t('flash_messages.message_1') }