2013-05-11 12 views
6

私はキュウリとカピバラで自分のアプリケーションをテストしようとしています。 私は、次のステップの定義を持っている:Capybara 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 

しかし、私はこのシナリオを実行するたびに私はエラーメッセージを受け取ります:

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' 

また、FactoryGirlがを私のレールテストコンソールで実行すると、image:nilが返されることがわかりました。

誰でも私が間違っていることを説明できますか?あなたが直接にパスを渡す必要があり

答えて

10

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

ここで何が起こっているがattach_fileが文字列ではなく、CarrierWaveアップローダーを期待していることです。アップローダー(@article_attributes.image)を渡すと、attach_fileはと呼ばれ、Uploader#pathが呼び出されます。まだ記事を保存していないので、アップロードされた画像が配置されるパスは無効です。

変数@article_attributesを呼び出すと、ハッシュだけでなく、実際には完全な記事オブジェクトなので、混乱することにも注意してください。それがあなたが望むなら、FactoryGirl.attributes_for(:article)を試してみてください。

+0

回答のタクシー!あなたが言ったように、 '@article_attributes = FactoryGirl.attributes_for(:article)'を使用しようとしました。しかし '@article_attributes [:image]'は '#'を返します。これを直接文字列パスに変換する方法はありますか? ' –

+0

'@article_attributes [:image] .path'? Fileオブジェクト(http://ruby-doc.org/core-2.0/File.html#method--path)からパスを取得する方法がないと、狂った世界になります。 – Taavo

+0

ありがとうございました!すべてのことが今働いています。 –

関連する問題