【发布时间】:2017-02-06 11:46:34
【问题描述】:
这是我在 Ruby on rails 中的模型
class Item < ApplicationRecord
has_attached_file :image,
:styles => { :medium => "400x400>", :thumb => "100x100>", :square => "300x300#" }, default_url: "/images/:style/missing.png"
validates_presence_of(:description, :color, :category, :size, :image)
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
belongs_to :user
end
我正在尝试使用 rspec 和 factory girl 覆盖测试中模型的图像属性来测试它。但我不能,因为 nil 不能完全填充内容类型验证 - 它必须是图像。因此,我们可以测试它是否是图像,或者是否包含在内。
describe Item, type: :model do
context "validations" do
let(:user) {create(:user)}
subject(:item) {
create(:item, user_id: user.id)
}
it "is not valid without an image" do
item[:image] = nil
expect(item).not_to be_valid
end
end
end
include ActionDispatch::TestProcess
FactoryGirl.define do
factory :item do
size "XS"
color "Orange"
category "Onesie"
description "Pokemon onesie"
image { fixture_file_upload(Rails.root.join('spec', 'files', 'images', 'pokemon_onesie.jpg'), 'image/png') }
user_id 1
end
end
【问题讨论】:
标签: ruby-on-rails validation rspec