我有以下代码来删除特定属性上的空格。
#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我遗漏了什么?
发布于 2011-09-09 20:15:05
在保存对象或手动调用valid?之前,不会运行验证。您的before_validation回调在当前示例中没有运行,因为您的验证从未被检查过。在您的测试中,我建议您先运行@part.valid?,然后再检查标题是否已更改为您期望的名称。
app/model/part.rb
class Part < ActiveRecord::Base
before_validation :strip_whitespace
protected
def strip_whitespace
self.title = self.title.strip
end
endspec/model/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当包含验证时,它将通过,当验证被注释掉时,它将失败。
发布于 2012-09-11 19:29:36
参考@danivovich示例
class Part < ActiveRecord::Base
before_validation :strip_whitespace
protected
def strip_whitespace
self.title = self.title.strip
end
end编写规范的正确方法是在strip_whitespace方法上单独编写规范,然后只检查模型类是否设置了回调,就像这样:
describe Part do
let(:record){ described_class.new }
it{ described_class._validation_callbacks.select{|cb| cb.kind.eql?(:before)}.collect(&:filter).should include(:strip_whitespace) }
#private methods
describe :strip_whitespace do
subject{ record.send(:strip_whitespace)} # I'm using send() because calling private method
before{ record.stub(:title).and_return(' foo ')
it "should strip white spaces" do
subject.should eq 'foo'
# or even shorter
should eq 'foo'
end
end
end如果在某些情况下需要跳过回调行为,请使用
before{ Part.skip_callback(:validation, :before, :strip_whitespace)}
before{ Part.set_callback( :validation, :before, :strip_whitespace)}更新20.01.2013
顺便说一句,我用RSpec匹配器写了一个gem来测试这个https://github.com/equivalent/shoulda-matchers-callbacks
一般来说,我根本不推荐回调。例如,在这个问题中它们是很好的,但是一旦你做了更复杂的事情,比如:
创建后->
指向用户的
的电子邮件
...then您应该创建自定义服务对象来处理此问题,并分别对它们进行测试。
https://stackoverflow.com/questions/7361036
复制相似问题