unit test in rails - model with paperclip

前端 未结 3 926
忘掉有多难
忘掉有多难 2021-01-31 16:27

I\'m trying to write a test for a model with a picture, using paperclip. I\'m using the test framework default, no shoulda or rspec. In this context, how should I test it? Shoul

3条回答
  •  情歌与酒
    2021-01-31 16:57

    I use FactoryGirl, setup the Model.

    #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
    

    then

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

    In the paperclip attachment specify where its going to be saved i.e.

    ...
    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
    

    ...

    then test both the attachment_definitions (as suggested by kwon) and the Dir.glob to check the file is saved

     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
    

    this way i'm sure its carrying out the correct directy/path create etc

提交回复
热议问题