Ruby on rails 4 Rspec 3-如何在模型试验中验证前处理
在我的模型中,我采用了一种前验证方法:Ruby on rails 4 Rspec 3-如何在模型试验中验证前处理,ruby-on-rails-4,factory-bot,rspec-rails,Ruby On Rails 4,Factory Bot,Rspec Rails,在我的模型中,我采用了一种前验证方法: class Post < ActiveRecord::Base before_validation :generate_url ... private def generate_url return unless self.url.blank? year = self.published_at.class == ActiveSupport::TimeWithZone ? self.published_at.year : Date
class Post < ActiveRecord::Base
before_validation :generate_url
...
private
def generate_url
return unless self.url.blank?
year = self.published_at.class == ActiveSupport::TimeWithZone ? self.published_at.year : DateTime.now.year
self.url = "#{year}/#{self.title.parameterize}"
end
spec/factories/post.rb
FactoryGirl.define do
factory :post do
user_id 1
title "myTitle"
content "myContent."
published false
published_at "2014-09-16 08:46:38"
end
end
# note : attribute url is generated with before_validation
让它在验证之前跳过
:
RSpec.describe Post, :type => :model do
before{ Post.skip_callback(:validation, :before, :generate_url) }
it { is_expected.to validate_presence_of(:user_id) }
it { is_expected.to validate_presence_of(:title) }
it { is_expected.to ensure_length_of(:title).is_at_least(5) }
it { is_expected.to validate_presence_of(:content) }
it { is_expected.to ensure_length_of(:content).is_at_least(10) }
it { is_expected.to validate_presence_of(:url) }
it { is_expected.to validate_uniqueness_of(:url) }
it { is_expected.to validate_presence_of(:published_at) }
end
您还可以提供一个块,以便只跳过该块的验证,如下所示:
RSpec.describe Post, :type => :model do
Post.skip_callback(:validation, :before, :generate_url) do
it { is_expected.to validate_presence_of(:user_id) }
it { is_expected.to validate_presence_of(:title) }
it { is_expected.to ensure_length_of(:title).is_at_least(5) }
it { is_expected.to validate_presence_of(:content) }
it { is_expected.to ensure_length_of(:content).is_at_least(10) }
it { is_expected.to validate_presence_of(:url) }
it { is_expected.to validate_uniqueness_of(:url) }
it { is_expected.to validate_presence_of(:published_at) }
end
end
注意:self不是零。self.title为零
根据规范,可以通过设置这样一个适当的主题来修复规范
RSpec.describe Post, :type => :model do
subject { FactoryGirl.create :post }
it { is_expected.to validate_presence_of(:title) }
end
然而,我尝试了这一点,错误仍然发生validate\u presence\u of
只需忽略主题并将其重置为Post.new
。它总是忽略预期的事情。我会说这是一个应该的错误。稍后我会检查他们的代码,或者至少提交问题
同时,不要像以前学校那样做
RSpec.describe Post, :type => :model do
describe #valiadations do
let!(:post) {Post.new.tap{|p|p.valid?} }
it "validated title" do
expect(post.errors_on[:title.size]).to eq(1)
end
end
end
发布生成url方法代码并完成详细答案的测试代码。您必须生成stub_url或向帖子提供一些默认数据,使generate_url正常工作。使用factories/post.rb向帖子提供数据,除非我错过了在规范处理过程中正确读取它的任何附加设置?
RSpec.describe Post, :type => :model do
subject { FactoryGirl.create :post }
it { is_expected.to validate_presence_of(:title) }
end
RSpec.describe Post, :type => :model do
describe #valiadations do
let!(:post) {Post.new.tap{|p|p.valid?} }
it "validated title" do
expect(post.errors_on[:title.size]).to eq(1)
end
end
end