Rspec2 测试 before_validation 方法 [英] Rspec2 testing a before_validation method
问题描述
我有以下内容来删除特定属性上的空格.
I have the following to remove the spaces on a specific attribute.
#before_validation :strip_whitespace
protected
def strip_whitespace
self.title = self.title.strip
end
我想测试一下.目前,我已经尝试过:
And I want to test it. For now, I've tried:
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
我错过了什么?
推荐答案
在保存对象或手动调用 valid?
之前,不会运行验证.您的 before_validation
回调没有在您当前的示例中运行,因为您的验证从未被检查过.在您的测试中,我建议您先运行 @part.valid?
,然后再检查标题是否已更改为您期望的那样.
Validations won't run until the object is saved, or you invoke valid?
manually. Your before_validation
callback isn't being run in your current example because your validations are never checked. In your test I would suggest that you run @part.valid?
before checking that the title is changed to what you expect it to be.
class Part < ActiveRecord::Base
before_validation :strip_whitespace
protected
def strip_whitespace
self.title = self.title.strip
end
end
spec/models/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
当包含验证时会通过,当验证被注释掉时会失败.
This will pass when the validation is included, and fails when the validation is commented out.
这篇关于Rspec2 测试 before_validation 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!