2013-05-11 49 views
6

我想用黃瓜和水豚來測試我的應用程序。 我有以下步驟定義:水豚FactoryGirl Carrierwave不能附加文件

Given(/^I fill in the create article form with the valid article data$/) do 
    @article_attributes = FactoryGirl.build(:article) 
    within("#new_article") do 
    fill_in('article_title', with: @article_attributes.title) 
    attach_file('article_image', @article_attributes.image) 
    fill_in('article_description', with: @article_attributes.description) 
    fill_in('article_key_words', with: @article_attributes.key_words) 
    fill_in('article_body', with: @article_attributes.body) 
    end 

我的文章廠是這樣的:

FactoryGirl.define do 
    factory :article do 
    sequence(:title) {|n| "Title #{n}"} 
    description 'Description' 
    key_words 'Key word' 
    image { File.open(File.join(Rails.root, '/spec/support/example.jpg')) } 
    body 'Lorem...' 
    association :admin, strategy: :build 
    end 
end 

這是我上傳的文件:

# encoding: UTF-8 
class ArticleImageUploader < CarrierWave::Uploader::Base 
    storage :file 
    def store_dir 
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" 
    end 
    def extension_white_list 
    %w(jpg jpeg gif png) 
    end 
end 

但每次我運行此場景時間我收到ERROR消息:

Given I fill in the create article form with the valid article data # features/step_definitions/blog_owner_creating_article.rb:1 
     cannot attach file, /uploads/article/image/1/example.jpg does not exist (Capybara::FileNotFound) 
     ./features/step_definitions/blog_owner_creating_article.rb:5:in `block (2 levels) in <top (required)>' 
     ./features/step_definitions/blog_owner_creating_article.rb:3:in `/^I fill in the create article form with the valid article data$/' 
     features/blog_owner_creating_article.feature:13:in `Given I fill in the create article form with the valid article data' 

我還發現,當我在我的rails測試控制檯中運行FactoryGirl.build(:article)時,FactoryGirl返回image:nil

有人能解釋我我做錯了嗎?

回答

10

您需要通過直接的路徑:

attach_file('article_image', File.join(Rails.root, '/spec/support/example.jpg')) 

這裏發生的事情是,attach_file需要一個字符串,而不是一個CarrierWave上傳。當你通過一個上傳器(@article_attributes.image),attach_fileUploader#to_s,其中調用Uploader#path。由於您尚未保存文章,因此上傳的圖片所在的路徑無效。

還要注意,調用變量@article_attributes令人困惑,因爲它實際上是一個完整的文章對象,而不僅僅是一個散列。如果這就是你想要的,你可能想嘗試FactoryGirl.attributes_for(:article)

+0

Thaks for answers!正如你所說的,我試圖使用'@article_attributes = FactoryGirl.attributes_for(:article)'。但'@article_attributes [:image]'返回'#'。有什麼方法可以將它轉換爲直接字符串路徑嗎?' – 2013-05-12 19:47:59

+0

'@article_attributes [:image] .path'?如果沒有辦法[從File對象獲取路徑](http://ruby-doc.org/core-2.0/File.html#method-i-path),那將是一個瘋狂的世界。 – Taavo 2013-05-12 21:37:10

+0

非常感謝!現在每件事都在起作用。 – 2013-05-13 05:37:56