Comparing rspec custom ActiveRecord::RecordInvalid errors messages

天涯浪子 提交于 2020-01-13 19:39:39

问题


Having the following in the model :

validates_uniqueness_of :title,
    if: proc { |item| item.item_type == 'tag' },
    case_sensitive: false,
    message: I18n.t('errors.key', value: "%{value}")

and trying to validate in rspec with the following :

expect { xxx }.to raise_error(
    ActiveRecord::RecordInvalid,
    I18n.t('errors.key', value: '...passing the title...')
)

Am stuck with the very close following :

ActiveRecord::RecordInvalid with "translated error",
got #<ActiveRecord::RecordInvalid: Validation failed: translated error>

The expectation awaits a value without quote, while the value sent has quote; it fails on that

I get the very same error with the default setup :

activerecord:
    errors:
      models:
        item:
          attributes:
            title:
              taken: 'translated error'

The same test passes with the followings :

expect { xxx }.to raise_error

expect { xxx }.to raise_error( ActiveRecord::RecordInvalid )

So does using the default setup :

Thanks if any help on that one


回答1:


ActiveRecord adds the prefix Validation failed: to the error message. Try this in your test instead:

expect { xxx }.to raise_error(
  ActiveRecord::RecordInvalid,
  "Validation failed: " + I18n.t('errors.key', value: '...passing the title...')
)

You can change this default by setting the following key in your language file:

en:
  activerecord:
    errors:
      messages:
        record_invalid: "Validation failed: %{errors}"


来源:https://stackoverflow.com/questions/45128434/comparing-rspec-custom-activerecordrecordinvalid-errors-messages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!