问题
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