测试文件上传

时间:2013-06-27 18:15:22

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

我有简单的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)。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我在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

希望一切都清楚!

相关问题