ruby-on-rails – Rspec2测试before_validation方法
发布时间:2020-12-17 04:22:32 所属栏目:百科 来源:网络整理
导读:我有以下内容删除特定属性上的空格. #before_validation :strip_whitespaceprotected def strip_whitespace self.title = self.title.strip end 我想测试一下.现在,我试过了: it "shouldn't create a new part with title beggining with space" do @part =
我有以下内容删除特定属性上的空格.
#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 这将在包含验证时通过,并在验证被注释掉时失败. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |