Paperclip with factory_girl on Rspec
2012-12-27
今日はPaperclip
なモデルをRspecでテストする際の注意事項についてメモ。
PaperclipとFactoryGirl
言わずもがな、Paperclipは、ファイルをアップロードするためのgemです。
# app/models/user.rb
class User < ActiveRecord::Base
attr_accessible :avatar
has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>" }
end
同様にFactoryGirlは、所謂fixture replacementのgemですね。
# This will guess the User class
FactoryGirl.define do
factory :user do
first_name "John"
last_name "Doe"
admin false
end
# This will use the User class (Admin would have been guessed)
factory :admin, class: User do
first_name "Admin"
last_name "User"
admin true
end
end
Paperclip::Shoulda::Matchers
paperclip
には独自のvalidationが幾つかありますが、それらをrspec
で検証する際、このPaperclip::Shoulda::Matchersを使います。
使い方は次の通り。
# spec/spec_helper.rb
require "paperclip/matchers"
RSpec.configure do |config|
#
# etc...
#
# 追加
config.include Paperclip::Shoulda::Matchers
end
上記の設定をすると、下記の通り、validation
のテストが簡単に書くことができます。
describe User do
it { should have_attached_file(:avatar) }
it { should validate_attachment_presence(:avatar) }
it { should validate_attachment_content_type(:avatar).
allowing('image/png', 'image/gif').
rejecting('text/plain', 'text/xml') }
it { should validate_attachment_size(:avatar).
less_than(2.megabytes) }
end
TextUnitを使った場合などは、以下からご確認くださいませ。
参考
rubydoc.info/gems/paperclip/Paperclip/Shoulda/Matchers
fixturefileupload
添付ファイルのテストをしたい場合にfixture_file_upload
を使うのですが、その際、以下のように設定を施しましょう。
# spec/factories/users.rb
include ActionDispatch::TestProcess # 追加
FactoryGirl.define do
factory :user do
name 'Takuya Kato'
avatar { fixture_file_upload("#{Rails.root}/spec/files/rails.png", "image/png") }
end
end
私の場合、保存先にAWS S3を使っているせいか、体感速度がとっても遅いのがネックです。 テストだけローカルの保存する(?)とか、何か他に上手な方法がないか探しているので、知っている方は教えて頂けると嬉しいです。