当我尝试在测试中使用自定义插值时,它们会失败。但是,每个方面都可以在开发环境中正常工作,并且测试工作没有自定义插值+ 有时它们可以使用自定义插值。
我的代码:
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'
我得到的错误是:
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
解析为nil
我的问题: 为什么它仅在测试环境中解析为nil而不是所有时间? (另一个测试成功地使用日期插入将文件添加到路径中)
答案 0 :(得分:1)
我认为问题在于您有未保存的Document
实例
您只需致电document = Document.new
,document.created_at
即nil
。
尝试使用Document
保存document = Document.create(...)
个实例,或在断言前调用document.save
。
或者您可以手动指定created_at
document = Document.new(created_at: Time.now)
或者您可以更新插值代码以使用nil
值,例如
Paperclip.interpolates :year do |attachment, style|
# it would be nil in case of created_at is nil
attachment.instance.created_at.try(:year)
end