8

キュウリとカピバラでアプリケーションをテストしようとしています。次のステップ定義があります。

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'

また、Rails テスト コンソールでimage:nil実行すると、 FactoryGirl が返されることもわかりました。FactoryGirl.build(:article)

誰かが私が間違っていることを説明してもらえますか?

4

1 に答える 1

13

パスを直接渡す必要があります。

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

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

また、変数の呼び出し@article_attributesは紛らわしいことに注意してください。これは、実際には単なるハッシュではなく完全な記事オブジェクトであるためです。それが必要な場合は、試してみてくださいFactoryGirl.attributes_for(:article)

于 2013-05-12T16:49:08.287 に答える