验证相同属性测试的状态和内容类型

时间:2017-02-06 11:46:34

标签: ruby-on-rails validation rspec

这是我在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和工厂女孩在测试中覆盖模型中的图像属性来测试它。但我不能,因为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

2 个答案:

答案 0 :(得分:0)

根据README 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

答案 1 :(得分:0)

我明白了。事实证明这很简单

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