Rspec2测试before_validation方法

Kle*_* S. 7 unit-testing rspec ruby-on-rails rspec2 ruby-on-rails-3

我有以下内容删除特定属性上的空格.

#before_validation :strip_whitespace

protected
  def strip_whitespace
    self.title = self.title.strip
  end
Run Code Online (Sandbox Code Playgroud)

我想测试一下.现在,我试过:

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

我错过了什么?

dan*_*ich 14

在保存对象或valid?手动调用之前,验证不会运行.您的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
Run Code Online (Sandbox Code Playgroud)

规格/型号/ 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
Run Code Online (Sandbox Code Playgroud)

这将在包含验证时通过,并在验证被注释掉时失败.