Capybara FactoryGirl Carrierwave无法附加档案

Ole*_*ous 6 cucumber capybara carrierwave factory-bot

我试图用黄瓜和水豚测试我的应用程序.我有以下步骤定义:

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
Run Code Online (Sandbox Code Playgroud)

我的文章工厂看起来像这样:

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
Run Code Online (Sandbox Code Playgroud)

这是我的上传文件:

# 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
Run Code Online (Sandbox Code Playgroud)

但每次我运行这个场景我都会得到错误消息:

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'
Run Code Online (Sandbox Code Playgroud)

我还发现image:nil当我FactoryGirl.build(:article)在rails测试控制台中运行时,FactoryGirl会返回.

有人可以解释一下我做错了吗?

Taa*_*avo 10

您需要直接传递路径:

attach_file('article_image', File.join(Rails.root, '/spec/support/example.jpg'))
Run Code Online (Sandbox Code Playgroud)

这里发生的是attach_file期望一个字符串,而不是CarrierWave上传器.当你传递一个uploader(@article_attributes.image),attach_file正在调用Uploader#to_s,调用Uploader#path.由于您尚未保存文章,因此上传图像所在的路径无效.

另请注意,调用变量@article_attributes会让人感到困惑,因为它实际上是一个完整的文章对象,而不仅仅是一个哈希.如果这是你想要的,你可能想尝试FactoryGirl.attributes_for(:article).