RSpec和ActiveRecord:无效方案的示例失败

时间:2012-03-17 08:33:31

标签: ruby ruby-on-rails-3 activerecord rspec

我是Rails的新手并试图用TDD和BDD编写应用程序。

现在,在其中一个模型中,对字段的长度进行了验证。有一个RSpec有一个例子来检查这个特定字段的长度验证。

这是Model类

class Section < ActiveRecord::Base

    # Validations
    validates_presence_of :name, length: { maximum: 50 }

end

和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

当我发出这个规范示例失败时出现以下错误

....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

我在这里错过了什么吗?

另外,请向我建议一些参考资料,以了解如何使用RSpec(和Shoulda)测试模型,尤其是关系。

1 个答案:

答案 0 :(得分:5)

validates_presence_of方法没有length选项。 您应该使用validates_length_of方法验证长度:

class Section < ActiveRecord::Base
  # Validations
  validates_presence_of :name
  validates_length_of :name, maximum: 50
end

或者使用rails3新的验证语法:

class Section < ActiveRecord::Base
  # Validations
  validates :name, presence: true, length: {maximum: 50}
end