yossico yossico - 2 months ago 25
Ruby Question

Rails Paperclip custom interpolation error on test

When I try to use custom interpolation on tests they fail. however, everythings works fine on development environment and the test worked without custom interpolation + sometimes they work with the custom interpolation.

my code:

class ActiveSupport::TestCase
fixtures :all
def file_fixture(filename = "sample_file.png")
File.new("test/fixtures/documents/#{filename}")
end
end

test 'document attachment must be from valid file extension' do
document = Document.new
document.appeal_id = Appeal.first.id
document.attachment = file_fixture('FailTest - bad filename extension.txt')
assert_not document.valid?, 'Document attachment should not be TXT'
document.attachment = file_fixture('Test - medical.pdf')
assert document.valid?, 'Document attachment with pdf extension should be valid'
end


application.rb:

Paperclip.interpolates :year do |attachment, style|
attachment.instance.created_at.year
end

Paperclip.interpolates :month do |attachment, style|
attachment.instance.created_at.month
end

Paperclip.interpolates :appeal_id do |attachment, style|
attachment.instance.appeal.id
end

Paperclip.interpolates :env do |attachment, style|
Rails.env
end

Paperclip.options[:command_path] = 'C:\Program Files (x86)\GnuWin32\bin'
Paperclip::Attachment.default_options[:default_url] = '/images/missing.jpg'
Paperclip::Attachment.default_options[:path] = ':rails_root/public/attachments/:env/:year/:month/:appeal_id/:hash.:extension'
Paperclip::Attachment.default_options[:url] = '/attachments/:env/:year/:month/:appeal_id/:hash.:extension'


The error I get is:

Minitest::UnexpectedError: NoMethodError: undefined method `year' for nil:NilClass
config/application.rb:27:in `block in <class:Application>'
test/models/document_test.rb:43:in `block in <class:DocumentTest>'


And this is because in the
:year
interpolation the
created_at
resolves to
nil


My Question:
Why does it resolves to nil only on the test environment and not all the time? (Another test successfuly added file to the path using the date interpulation)

Answer

I think the problem is that you have unsaved Document instance.
You just call document = Document.new so document.created_at is nil.

Try to get saved Document instance with document = Document.create(...) or by calling document.save before assertions.

Or you can manually assign created_at like
document = Document.new(created_at: Time.now)

Or you can update interpolations code to work with nil values like

Paperclip.interpolates :year do |attachment, style|
  # it would be nil in case of created_at is nil
  attachment.instance.created_at.try(:year) 
end
Comments