【发布时间】:2016-08-27 12:11:39
【问题描述】:
我有一个 Rails 5 设置,其中 RSpec 无法检查模型子类的验证。如果我在控制台中手动构建对象,我可以看到应该阻止记录有效的错误。
基础模型:
class Article < ApplicationRecord
belongs_to :author, class_name: User
validates :author, presence: { message: "L'utente autore dell'articolo è obbligatorio." }
validates :title, presence: { message: "Il titolo dell'articolo è obbligatorio." }
end
继承自 Article 的模型:
class LongArticle < Article
mount_uploader :thumbnail, LongArticleThumbnailUploader
validates :excerpt, presence: { message: "L'estratto dell'articolo è obbligatorio." }
validates :thumbnail, presence: { message: "L'immagine di anteprima dell'articolo è obbligatoria." }
end
这些型号的工厂 (FactoryGirl):
FactoryGirl.define do
factory :article do
association :author, factory: :author
title "Giacomo Puccini: Tosca"
factory :long_article do
type "LongArticle"
excerpt "<p>Teatro alla Scala: immenso Franco Corelli.</p>"
thumbnail { Rack::Test::UploadedFile.new(File.join(Rails.root, 'spec', 'support', 'images', 'unresized-long-article-thumbnail.jpg')) }
end
end
end
这是不起作用的 RSpec:
require 'rails_helper'
RSpec.describe LongArticle, type: :model do
describe "is valid with mandatory fields" do
it "should be valid with if all mandatory fields are filled" do
article = FactoryGirl.create(:long_article)
expect(article).to be_valid
end
it "should have an excerpt" do
article = FactoryGirl.create(:long_article)
article.excerpt = nil
expect(article).not_to be_valid
end
it "should have the thumbnail" do
article = FactoryGirl.create(:long_article)
article.thumbnail = nil
expect(article).not_to be_valid
end
end
end
第一个规范通过,其他两个没有。 我尝试使用相同的值测试控制台中的所有内容,并且它可以正常工作,这意味着记录应该是无效的。
是否有可能使用 RSpec 子类中的验证不起作用?
【问题讨论】:
-
在你搞清楚的时候,我建议你查看github.com/thoughtbot/shoulda-matchers 以轻松测试验证。
-
您也可以使用调试器或biding.pry 进入规范并手动运行
article.valid?找出原因。
标签: ruby-on-rails validation rspec