テストでカスタム補間を使用しようとすると失敗します。しかし、すべての開発環境で正常に動作し、テストはカスタム補間なしで働いた+ 時々彼らはカスタム補間で動作します。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つのテストは、日付の補間を使用してファイルを正常に追加しました)
あなた.tryよう
nil
値で動作するように更新することができのように割り当てることができます例が働いていた(年)。私は検証の問題のために保存されていないと思うので、created_atには何もありません。 ...それについてもっと学ぶ必要がある、とにかく - 感謝! – yossico
はい、私は 'try'が最適な解決策だと思います。ところで、それは ':year'と' nil'で補間しますか? – Aleksey