Reputation: 15985
I am newbie to Rails and trying to write application with TDD and BDD.
Now in one of the models there is a validation on length of a field. There is an RSpec having an example which checks length validation of this specific field.
Here is Model class
class Section < ActiveRecord::Base
# Validations
validates_presence_of :name, length: { maximum: 50 }
end
and RSpec
require 'spec_helper'
describe Section do
before do
@section = Section.new(name:'Test')
end
subject { @section }
# Check for attribute accessor methods
it { should respond_to(:name) }
# Sanity check, verifying that the @section object is initially valid
it { should be_valid }
describe "when name is not present" do
before { @section.name = "" }
it { should_not be_valid }
end
describe "when name is too long" do
before { @section.name = "a" * 52 }
it { should_not be_valid }
end
end
When I rung this spec example fails with following error
....F......
Failures:
1) Section when name is too long
Failure/Error: it { should_not be_valid }
expected valid? to return false, got true
# ./spec/models/section_spec.rb:24:in `block (3 levels) in <top (required)>'
Finished in 0.17311 seconds
11 examples, 1 failure
Am I missing something here?
Also please suggest me some references to learn how Models should be tested especially relationship using RSpec (and Shoulda).
Upvotes: 1
Views: 730
Reputation: 130
The validates_presence_of
method does not have length
option.
You should validate length with validates_length_of
method:
class Section < ActiveRecord::Base
# Validations
validates_presence_of :name
validates_length_of :name, maximum: 50
end
Or use rails3 new validation syntax:
class Section < ActiveRecord::Base
# Validations
validates :name, presence: true, length: {maximum: 50}
end
Upvotes: 5