Capybara FactoryGirl Carrierwave cannot attach file

I am trying to test my application with cucumber and capybara. I have the following step definition:

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 

My factory article looks like this:

 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 

And this is my bootloader file:

 # 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 

But every time I run this script, I get an ERROR message:

 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' 

I also found that FactoryGirl returns image:nil when I run FactoryGirl.build(:article) in my rails test console.

Can someone explain to me what I'm doing wrong, please?

+6
source share
1 answer

You need to pass the path directly:

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

What happens here is that attach_file expects a string, not a CarrierWave loader. When you pass the loader ( @article_attributes.image ) to it, attach_file calls Uploader#to_s , which calls Uploader#path . Since you have not yet saved the article, the path that the downloaded image will be located is invalid.

Note that calling your @article_attributes variable @article_attributes confusing, as this is actually a complete article object, not just a hash. If you want, you can try FactoryGirl.attributes_for(:article) .

+10
source

Source: https://habr.com/ru/post/944790/


All Articles