我想对我的功能测试应用验证检查,例如:
click_button 'Submit'
expect(page).to have_content "Question can't be blank"
我正在使用I18n功能,并希望使用t()
帮助器生成消息:
expect(page).to have_content t('errors.messages.blank')
但这仅检查"can't be blank"
。但我需要检查question
字段上的错误。为什么我需要完整的消息?实际上,如果唯一关注的是与字段相关的错误,我们可以通过以下方式来解决这个问题:
expect(find('.question-wrapper')).to have_content t('errors.messages.blank')
但有时错误发生在表单中未使用的字段上,或:base
上。假设我们有一个表单来输入一个问题及其答案作为嵌套属性(它有一个“添加新答案”按钮,使用JavaScript创建新的Answer
字段集),并且如果表单是在没有提交的情况下提交,则会出现这些错误任何答案:
expect(page).to have_content "There should be at least 2 answers"
expect(page).to have_content "Correct answer must be selected"
如何I18n'ize这个?我们无法检查上述.question-wrapper
中的任何字段,因为"at least 2 answers"
未绑定到任何属性(或者即使它是answers
,但它不在表格)和正确答案收音机不存在,因为表格没有任何答案提交(没有点击我上面提到的“添加新答案”按钮)。
我目前正在使用一个hacky帮手,如:
# spec/support/helpers/i18n_helpers.rb
def full_error(model_class, attribute, message)
@_i18n_dummies ||= {}
@_i18n_dummies[model_class] ||= model_class.new
@_i18n_dummies[model_class].errors.full_message(
attribute,
@_i18n_dummies[model_class].errors.generate_message(attribute, message)
)
end
做出上述期望:
# spec/features/question_spec.rb
expect(page).to have_content full_error(Question, :answers, :many) # A custom validator
expect(page).to have_content full_error(Question, :correct_answer, :blank)