使用Capybara attach_file方法测试上传文件时遇到问题

 W蓝尾蝶SUH_435 发布于 2023-01-02 06:50

我在使用Capybara的attach_file方法测试图像上传是否与回形针配合使用时遇到了麻烦.

rspec返回以下错误:失败:

1) Upload Background Image cannot upload a background image
 Failure/Error: page.attach_file('#artist_background_image', Rails.root +         'spec/Fixtures/Snow.jpg')
 Capybara::ElementNotFound:
   Unable to find file field "#artist_background_image"
 # ./spec/models/artist_spec.rb:65:in `block (2 levels) in '

我的测试列在下面.我假设选择文件按钮是attach_file的选择器,所以我使用了选择器'#artist_background_page'的id.

describe 'Upload Background Image', js: true do
  before :each do
    p '================='
    pp Artist.all
    @artist = Artist.first || Artist.create(artist_name:'Double Stuff Oreos', email:'i@love.oreos', password:'letmein')
    visit "/artists/" + @artist.id.to_s
    pp @artist.id
    pp @artist.artist_name
    p @artist.errors.full_messages
    click_button 'Log in'
    fill_in 'Email', with: 'i@love.oreos'
    fill_in 'Password', with: 'letmein'
    page.find('#loginButtonModal').click
    page.find('#addBackgroundImagePrompt').click
    page.attach_file('#artist_background_image', Rails.root + 'spec/Fixtures/Snow.jpg')
    p Rails.root + 'spec/Fixtures/Snow.jpg'
    click_button 'upload'
  end

  it "cannot upload a background image", js: true do
    backgroundURL = @artist.background_image.url.include?('Snow.jpg')
    p @artist.background_image.url
    expect(backgroundURL).to be_truthy
  end
end

但是当我将选择器更改为'artist_background_page'而没有id'#'符号时.rspec给了我不同的错误:

...."================="
[]
"is_active_session is called"
#
1
"Double Stuff Oreos"
[]
"is_active_session is called"
#
"/background_images/original/missing.png"
"Hello from update"
"Logged in!"

An error occurred in an after hook
ActiveRecord::RecordNotFound: Couldn't find Artist with 'id'=1
occurred at /Users/shuo/.rvm/gems/ruby-2.1.2/gems/activerecord- 4.1.4/lib/active_record/relation/finder_methods.rb:320:in `raise_record_not_found_exception!'

F....

Failures:

1) Upload Background Image cannot upload a background image
   Failure/Error: expect(backgroundURL).to be_truthy
   expected: truthy value
        got: false
 # ./spec/models/artist_spec.rb:74:in `block (2 levels) in '

在这种情况下,模型已创建,但错误表明由于某种原因无法找到它...是否有任何其他方法可用于附加capybara文件并测试成功上传?

失败的可能性:

    文件上传的路径错误

    使用错误的方法或无效使用方法

    服务器有问题

El'Magnifico.. 14

这个错误:

Capybara::ElementNotFound:
   Unable to find file field "#artist_background_image"

表明水豚找不到名字的字段#artist_background_image.您需要做的是按名称引用文件上载字段.

假设你有


然后你可以像这样引用该字段:

page.attach_file('file_upload', Rails.root + 'spec/Fixtures/Snow.jpg')

有了它,capybara将知道要上传的字段.

我知道这是一个迟到的回应,但我认为这将有助于其他人面对这个问题.

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有