【问题标题】:Validating presence and content type for the same property test验证相同属性测试的存在和内容类型
【发布时间】: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


    【解决方案1】:

    我想通了。原来这很简单

    it "is not valid without an image" do
      expect{item[:image] = nil}.to raise_error(NameError)
    end
    

    【讨论】:

      【解决方案2】:

      根据自述文件here,您可以使用单个验证器语句进行多个验证。像这样的:

      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)
        validates_attachment :image,
          content_type: { :content_type => /\Aimage\/.*\Z/ }
          presence: true
      
        belongs_to :user
      end
      

      【讨论】:

      • 还是不知道怎么测试
      猜你喜欢
      • 2011-04-24
      • 2022-12-11
      • 1970-01-01
      • 2011-06-24
      • 2011-11-21
      • 1970-01-01
      • 2020-04-26
      • 2011-12-24
      • 1970-01-01
      相关资源
      最近更新 更多