سؤال

أحاول كتابة اختبار لنموذج به صورة، باستخدام PaperClip. أنا أستخدم اختبار إطار الاختبار الافتراضي، لا ينبغي أن يكون ينبغي عليه أو RSPEC. في هذا السياق، كيف يمكنني اختباره؟ هل يجب علي تحميل ملف حقا؟ كيف يجب أن أضيف ملف إلى لاعبا اساسيا؟

هل كانت مفيدة؟

المحلول

إضافة ملف إلى نموذج ميت بسيط. علي سبيل المثال:

@post = Post.new
@post.attachment = File.new("test/fixtures/sample_file.png")
# Replace attachment= with the name of your paperclip attachment

في هذه الحالة يجب عليك وضع الملف في test/fixtures دير.

أنا عادة ما أجري المساعد قليلا في بلدي test_helper.rb

def sample_file(filename = "sample_file.png")
  File.new("test/fixtures/#{filename}")
end

ثم

@post.attachment = sample_file("filename.txt")

إذا كنت تستخدم شيئا مثل فتاة المصنع بدلا من تركيبات هذا يصبح أسهل.

نصائح أخرى

هذا في RSPEC، ولكن يمكن تشغيله بسهولة

before do # setup
  @file = File.new(File.join(RAILS_ROOT, "/spec/fixtures/paperclip", "photo.jpg"), 'rb')
  @model = Model.create!(@valid_attributes.merge(:photo => @file))
end

it "should receive photo_file_name from :photo" do # def .... || should ....
  @model.photo_file_name.should == "photo.jpg"
  # assert_equal "photo.jpg", @model.photo_file_name
end

نظرا لأن PaperClip تم اختباره جيدا، فأنا عادة لا أركز كثيرا على فعل "التحميل"، إلا إذا كنت أفعل شيئا غير عادي. لكنني سأحاول التركيز بشكل أكبر على ضمان تكوينات المرفق، فيما يتعلق بالنموذج الذي ينتمي إليه، تلبي احتياجاتي.

it "should have an attachment :path of :rails_root/path/:basename.:extension" do
  Model.attachment_definitions[:photo][:path].should == ":rails_root/path/:basename.:extension"
  # assert_equal ":rails_root/path/:basename.:extension", Model.attachment_definitions[:photo][:path]
end

يمكن العثور على جميع الأشياء الجيدة في Model.attachment_definitions.

يمكنني استخدام FactoryGirl، إعداد النموذج.

#photos.rb
FactoryGirl.define do
  factory :photo do
    image File.new(File.join(Rails.root, 'spec', 'fixtures', 'files', 'testimg1.jpg'))
  description "testimg1 description"
  end # factory :photo
 end

ومن بعد

 # in spec

before(:each) { @user = FactoryGirl.create(:user, :with_photo) }

في مرفق PaperClip تحديد المكان الذي سيتم حفظه IE

...
the_path= "/:user_id/:basename.:extension"
if Rails.env.test?
   the_path= ":rails_root/tmp/" + the_path
end
has_attached_file :image,  :default_url => ActionController::Base.helpers.asset_path('missing.png'),
:path => the_path, :url => ':s3_domain_url'

Paperclip.interpolates :user_id do |attachment, style|
   attachment.instance.user_id.to_s
end

...

ثم قم باختبار كلا من الملحق_إدخال (كما اقترحه Kwon) و Dir.Glob للتحقق من الملف

 it "saves in path of user.id/filename" do
    expect(Dir.glob(File.join(Rails.root, 'tmp', @user.id.to_s, @user.photo.image.instance.image_file_name)).empty?).to be(false)
 end

بهذه الطريقة أنا متأكد من أنها تنشئ Directy / المسار الصحيح الخلق وما إلى ذلك

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top