2013-06-27 87 views
0

我有簡單的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)生成此文件。

感謝您的幫助。

回答

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 

希望一切都清楚!

+0

這不完全是我所需要的。我想我通過將測試文件移動到'spec/fixtures'中,然後在'之前:每個'塊中'@file = fixture_file_upload'/links.txt','text/plain''來解決它。 –

+0

剛剛測試過這個File.open,它工作的很好。不知道哪種方式更好。 –