我有以下内容删除特定属性上的空格.
- #before_validation :strip_whitespace
- protected
- def strip_whitespace
- self.title = self.title.strip
- end
我想测试一下.现在,我试过了:
- it "shouldn't create a new part with title beggining with space" do
- @part = Part.new(@attr.merge(:title => " Test"))
- @part.title.should.eql?("Test")
- end
我错过了什么?
解决方法
在保存对象或调用有效之前,验证不会运行?手动.您的before_validation回调未在当前示例中运行,因为您的验证永远不会被检查.在你的测试中,我建议你运行@ part.valid?在检查标题是否改变为您期望的标题之前.
应用程序/模型/ part.rb
- class Part < ActiveRecord::Base
- before_validation :strip_whitespace
- protected
- def strip_whitespace
- self.title = self.title.strip
- end
- end
规格/型号/ part_spec.rb
- require 'spec_helper'
- describe Part do
- it "should remove extra space when validated" do
- part = Part.new(:title => " Test")
- part.valid?
- part.title.should == "Test"
- end
- end
这将在包含验证时通过,并在验证被注释掉时失败.