2016-09-27 15 views
0

テストでカスタム補間を使用しようとすると失敗します。しかし、すべての開発環境で正常に動作し、テストはカスタム補間なしで働いた+ 時々彼らはカスタム補間で動作します。Rails Paperclipテストでのカスタム補間エラー

私のコード:

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:

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

そして:year補間にcreated_atはに解決するので、これは次のとおりです。

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' 

私が手にエラーがありますnil

私の質問: なぜ、テスト環境だけではなく、すべての時間で終わらないと解決するのですか? (もう1つのテストは、日付の補間を使用してファイルを正常に追加しました)

答えて

1

私は問題があなたに保存されていると思いますDocumentインスタンスです。
document = Document.newに電話すると、document.created_atnilとなります。

Documentインスタンスをdocument = Document.create(...)で保存するか、アサーションの前にdocument.saveを呼び出してみてください。

それとも、手動でcreated_at document = Document.new(created_at: Time.now)

それとも、補間コードが

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

あなた.tryようnil値で動作するように更新することができ
のように割り当てることができます例が働いていた(年)。私は検証の問題のために保存されていないと思うので、created_atには何もありません。 ...それについてもっと学ぶ必要がある、とにかく - 感謝! – yossico

+0

はい、私は 'try'が最適な解決策だと思います。ところで、それは ':year'と' nil'で補間しますか? – Aleksey

関連する問題