如何使用Capybara测试attach_file(Rails 4)

时间:2014-08-15 18:22:19

标签: ruby-on-rails

我想测试将图像添加到应用程序的功能。 我怎样才能做到这一点。 attach_file方法不起作用。我不知道为什么。 这是模型:

class Card < ActiveRecord::Base
  belongs_to :user
  has_attached_file :picture, styles: { medium: "300x300>", thumb: "100x100>" }
  validates_attachment_content_type :picture, content_type: /\Aimage\/.*\Z/
  validates_attachment_size :picture, :in => 0.megabytes..2.megabytes
  validates :original_text, :translated_text, :review_date, :user_id, :picture, presence:   true

这是rspec:

it "check add card" do
    FactoryGirl.create(:card, user_id: @user.id)
    visit root_path
    click_on 'Add card'
    attach_file('card[picture]', File.join(Rails.root, '/spddec/features/test.png' ))
    ...
    ...
    click_on 'Create Card'
    expect(page).to have_content('тест')
  end

这是观点:

<%= simple_form_for([current_user, @card]) do |f| %>
  <%= f.input :picture, label: 'Include Picture' %>
  <%= f.input :original_text, label: 'Original Text'  %>
  <%= f.input :translated_text, label: 'Translated Text' %>
  <%= f.input :review_date, label: 'Дата просмотра' %>
  <%= f.button :submit %>
<% end %>

 (HTML)
<input class="file required" id="card_picture" name="card[picture]" type="file" /></div>

这是我得到的错误:

Failure/Error: FactoryGirl.create(:card, user_id: @user.id)
 ActiveRecord::RecordInvalid:
   Validation failed: Picture can't be blank

1 个答案:

答案 0 :(得分:0)

请尝试使用此代码link

page.attach_file(picture, '/path/to/file.png')

或此代码link

it "can upload a image" do
  post :picture, avatar: fixture_file_upload('files/spongebob.png', 'image/png')
  response.should be_success
end

阅读此question的答案,我认为这对您的问题更有帮助。