【问题标题】:Testing file uploading测试文件上传
【发布时间】:2013-06-27 18:15:21
【问题描述】:

我有简单的 CSV 上传:

型号:

def import_links(file)
  CSV.foreach(file.path) do |row|
    links.create(Hash[%w(url text description).zip row])
  end 
end

表格:

<%= form_tag import_links_board_path(@board), multipart: true do %>
  <%= file_field_tag :file %><br/>
  <%= submit_tag "Import" %>
<% end %>

控制器:

def import_links
  @board = Board.find(params[:id])
  @board.import_links(params[:file])
  redirect_to @board
end

我想测试这个模型的#import_links 方法,所以可能想要类似的东西:

before :each do
  @file = ...
end

不幸的是,我不知道如何生成此文件(手动生成,或者使用 FactoryGirl 更好)。

感谢您的帮助。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 rspec


    【解决方案1】:

    我已经在 rspec 中使用这个助手进行集成测试:

    module PathHelpers
      def file_path(name)
        File.join("spec", "support", "files", name)
      end
    end
    
    RSpec.configuration.include PathHelpers
    

    然后,将您的测试文件放在spec/support/files 中,您可以在测试中使用它:

    scenario "create new estimate" do
      visit new_estimate_path
    
      fill_in 'Title', with: 'Cool estimate'
      attach_file 'CSV', file_path('estimate_items.csv')
    
      expect { click_button "Create estimate" }.to change(Estimate, :count).by(1)
    end
    

    对于 FactoryGirl 工厂,我有这样的东西:

    FactoryGirl.define do
      factory :estimate_upload do
        estimate
        excel File.open(File.join(Rails.root, 'spec', 'support', 'files', 'estimate_items.csv'))
      end
    end
    

    希望一切都清楚!

    【讨论】:

    • 这不是我所需要的。我想我通过将测试文件移动到spec/fixtures,然后在before :each 块中移动@file = fixture_file_upload '/links.txt', 'text/plain' 来解决它。
    • 刚刚测试了这个 File.open,它也可以正常工作。不知道哪种方式更好。
    猜你喜欢
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-30
    • 2011-10-18
    • 2019-12-28
    • 2017-02-03
    相关资源
    最近更新 更多