ruby-on-rails – Rspec,shoulda,validate_uniqueness_of具有范围和错误的错误消息

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Rspec,shoulda,validate_uniqueness_of具有范围和错误的错误消息前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下Rspec测试:
  1. describe Productlimit do
  2.  
  3. before(:each) do
  4. @productlimit = Factory.create(:productlimit,:user => Factory.create(:user))
  5. end
  6.  
  7. subject { @productlimit }
  8.  
  9. ...
  10.  
  11. it { should validate_uniqueness_of(:price_cents).scoped_to(:direction_down,:currency,:market_id,:user_id) }
  12. ...
  13. end

但我得到以下混乱的错误

  1. 1) Productlimit
  2. Failure/Error: it { should validate_uniqueness_of(:price_cents).scoped_to(:direction_down,:user_id) }
  3. Expected errors to include "has already been taken" when price_cents is set to 9530,got errors: ["direction_down has already been taken (false)"]

你可以帮我吗?我不明白为什么这不工作,因为错误信息似乎是正确的?

编辑:

在其他情况下也会发生这种情况:

  1. # product_spec.rb
  2. ...
  3. it { should validate_numericality_of(:price).with_message("price_cents must be greater than 0 (0)") }
  4.  
  5. # rake spec:models
  6. Failure/Error: it { should validate_numericality_of(:price).with_message("price_cents must be greater than 0 (0)") }
  7. Expected errors to include "price_cents must be greater than 0 (0)" when price is set to "abcd",got errors: ["price_cents must be greater than 0 (0)"]

解决方法

要检查validate_uniqueness_of(:field),但是为此,您应该在数据库中租用一个记录来检查uniquness约束.
这是….
  1. before do
  2. @country = FactoryGirl.create(:country,:id =>"a0000007-0000-0000-0000-000000000009",:currency_id => "a0000006-0000-0000-0000-000000000004",:merchant_id => "a0000001-0000-0000-0000-000000000002",:country_code => 'CAN',:name => 'Canada')
  3. end

验证唯一性

  1. it { should validate_uniqueness_of(:country_code)}

它会努力尝试.

猜你在找的Ruby相关文章