2010-10-29 19 views
0

有問題測試(工作)上傳在我的Rails應用程序(使用2.3.8):測試文件上傳的Rails:不能轉換的ActionController :: TestUploadedFile轉換成String

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 

控制器剛剛分配散裝PARAMS

@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的。

回答

1

也許rails actioncontroller測試上傳文件由於某種原因與File.size不起作用?

這是與大小交易的唯一行: http://github.com/jnunemaker/joint/blob/master/lib/joint.rb#L46

嘗試做File.size(...),其中...是夾具文件上傳。看看是否有錯誤。如果是這樣,那麼可能需要調整軌道。

我測試文件上傳時往往實際使用是這樣的:

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 

不是最漂亮的,但它能夠完成任務。

+0

謝謝約翰。看起來比我更漂亮的比我的http://ap.rubyonrails.org/classes/ActionController/TestUploadedFile.html :)我忽略了它是File.size是在測試文件上進行釣魚。 – oliverbarnes 2010-11-04 07:02:56