2013-05-11 52 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