I am fighting with an error using rspec-on-rails-matchers.
I have a model called “Centro” based in this table
create_table “centros”, :force => true do |t|
t.string “nombre”
t.string “cif”
t.string “domicilio”
t.string “codigo_postal”
t.string “poblacion”
t.string “provincia”
t.string “subdominio”
t.datetime “created_at”
t.datetime “updated_at”
endd
And I want to spec that the ‘nombre’ field should be unique.
describe Centro do
before(:each) do
@centro = Centro.new
end
it do
@centro.should validate_uniqueness_of(:nombre)
end
end
and the model:
class Centro < ActiveRecord::Base
validates_uniqueness_of :nombre
end
This should pass but I have the error:
1)
‘Centro should model to validate the uniqueness of nombre’ FAILED
expected “model to validate the uniqueness of nombre” but got #<Centro
id: nil, nombre: nil, cif: nil, domicilio: nil, codigo_postal: nil,
poblacion: nil, provincia: nil, subdominio: nil, created_at: nil,
updated_at: nil>
./spec/models/centro_spec.rb:18:
I have inspect the validate_uniqueness_of method and try several things
until I think I found the culprit.
The original code, that fails
def validate_uniqueness_of(attribute)
return simple_matcher(“model to validate the uniqueness of
#{attribute}”) do |model|
model.class.stub!(:find).and_return(true)
!model.valid? && model.errors.invalid?(attribute)
end
end
But this works (obviously I also define a @valid_attribute hash)
def validate_uniqueness_of(attribute)
return simple_matcher(“model to validate the uniqueness of
#{attribute}”) do |model|
model.class.create!(@valid_attributes)
model.nombre = @valid_attributes[:nombre]
!model.valid? && model.errors.invalid?(attribute)
end
end
And the question.
What issue can be with mocking the find method in the class?
What can I try?
Thanks
Juanma.