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

Ami*_*tel 1 ruby activerecord rspec ruby-on-rails-3

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

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

这是Model类

class Section < ActiveRecord::Base

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

end
Run Code Online (Sandbox Code Playgroud)

和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
Run Code Online (Sandbox Code Playgroud)

当我响了这个规范示例失败并出现以下错误

....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
Run Code Online (Sandbox Code Playgroud)

我在这里错过了什么吗?

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

小智 5

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

class Section < ActiveRecord::Base
  # Validations
  validates_presence_of :name
  validates_length_of :name, maximum: 50
end
Run Code Online (Sandbox Code Playgroud)

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

class Section < ActiveRecord::Base
  # Validations
  validates :name, presence: true, length: {maximum: 50}
end
Run Code Online (Sandbox Code Playgroud)