Rspec, shoulda, validate_uniqueness_of with scope and wrong error message

BvuRVKyUVlViVIc7 picture BvuRVKyUVlViVIc7 · Jul 3, 2011 · Viewed 10.7k times · Source

I have following Rspec test:

describe Productlimit do

  before(:each) do 
    @productlimit = Factory.create(:productlimit, :user => Factory.create(:user))
  end

  subject { @productlimit }

  ...

  it { should validate_uniqueness_of(:price_cents).scoped_to(:direction_down, :currency, :market_id, :user_id) }
  ...
end

But I get following confusing error:

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

Can you help me? I don't understand why this isn't working, because the error message seems to be correct?

EDIT:

This happens too in other situations as well:

# product_spec.rb
...
it { should validate_numericality_of(:price).with_message("price_cents must be greater than 0 (0)") }  

# rake spec:models
Failure/Error: it { should validate_numericality_of(:price).with_message("price_cents must be greater than 0 (0)") }
   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)"]

Answer

Rameshwar Vyevhare picture Rameshwar Vyevhare · Nov 23, 2011

To check validate_uniqueness_of(:field) but for this you should at lease one record in database to check uniquness constrain. Here is....

before do
  @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')
end

To validate uniqueness

it { should validate_uniqueness_of(:country_code)}

It will work out try it out.