在我的 Rails 应用程序(使用 2.3.8)中测试(工作)上传时遇到问题:
class ProfilesControllerTest < ActionController::TestCase
test "creates a new profile" do
fixture_image = fixture_file_upload("#{RAILS_ROOT}/test/fixtures/files/avatar.jpg", 'image/jpeg')
post :create, :profile=>{:username=>'johndoe',
:password=>'mypass',
:avatar => fixture_image
}, :html => { :multipart => true }
assert_response :success
assert_not_nil Profile.find_by_username("johndoe")
assert_not_nil Profile.find_by_username("johndoe").avatar
end
end
Controller 只是批量分配参数
@profile = Profile.new(params[:profile])
@profile.save
模型使用 Joint处理上传:
class Profile
include MongoMapper::Document
plugin Joint
attachment :avatar
end
运行测试时出现此错误:
1) Error:
test_creates_a_new_profile(Api::ProfilesControllerTest):
TypeError: can't convert ActionController::TestUploadedFile into String
(eval):15:in `size'
(eval):15:in `avatar='
/Users/oliver/.rvm/gems/ruby-1.8.7-p302/gems/mongo_mapper-0.8.6/lib/mongo_mapper/plugins/keys.rb:183:in `send'
什么给了?显然 avatar= setter 将处理实际上传的文件,但不会处理 TestUploadedFile 的文件。
最佳答案
也许 rails actioncontroller 测试上传文件由于某些原因无法使用 File.size?
这是唯一处理大小的行: http://github.com/jnunemaker/joint/blob/master/lib/joint.rb#L46
尝试执行 File.size(...) ,其中 ... 是夹具文件上传。看看是不是报错。如果是这样,那么可能需要调整 Rails。
我在测试文件上传时经常使用这样的东西:
def uploaded_file(path)
pathname = Rails.root + 'test/fixtures/' + path
filename = File.basename(path)
tempfile = Tempfile.new(filename)
content_type = MIME::Types.type_for(pathname.to_s).to_s
FileUtils.copy_file(pathname, tempfile.path)
(class << tempfile; self end).class_eval do
alias local_path path
define_method(:original_filename) { filename }
define_method(:content_type) { content_type }
end
return tempfile
end
不是最漂亮的,但它完成了工作。
关于ruby-on-rails - 在 Rails 中测试文件上传:无法将 ActionController::TestUploadedFile 转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4051726/