[英]Rails: RSpec fails validations of model subclass
我有一個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是否有可能無法在子類中進行驗證?
很抱歉造成您的延誤,但我想我已經弄清了什么原因破壞了我的考試。
實際上,問題是兩個,而不是我最初想到的一個。
第一次測試: should have an excerpt
根據juanitofatas的建議,我在FactoryGirl建立我的模型的byebug
行之后添加了一條byebug
行。 我注意到實例化的模型具有class Article
而不是LongArticle
。
我突然注意到FactoryGirl在首次遇到factory :article do
時實例化了基礎工廠的模型。 然后,它將添加或覆蓋定義到內部工廠中的屬性,並將type
屬性視為任何其他屬性,而無需考慮它會驅動STI。
LongArticle
工廠應該被定義為完全不同的模型,與Article
相同。
第二項測試: should have the thumbnail
這有點愚蠢……我在CarrierWave上傳器中定義了default_url
方法,實際上,這是所需的行為。 測試已更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.