- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要使用 Capybara 和 Selenium 测试文件上传页面。
我写了这个测试:
require 'rails_helper'
describe 'Images', type: :feature do
before(:each) do
@user = create(:user)
visit '/users/sign_in'
fill_in 'sing-in-email-input', with: @user.email
fill_in 'sign-in-password-input', with: @user.password
click_button 'btn-sign-in'
visit '/categories'
click_on 'btn-new-category'
expect(current_path) == new_category_path
fill_in 'category_name', with: 'Test'
click_button 'btn-create category'
visit '/categories'
first('.fa', :visible => false).click
expect(current_path) == category_path(id: Category.last.slug.to_s)
end
it 'should allow a registered user to create image and go to it page', js: true do
click_on 'btn-upload-images'
expect(current_path) == new_image_path(id: Category.last.slug.to_s)
attach_file('image[image]',
File.join(Rails.root, '/spec/fixtures/solnce-kosmos-merkuriy.jpg'), :visible => false)
click_on('btn-upload-img')
end
end
我无法继续编写此测试并检查此图片是否已成功上传,因为在这一行:
click_on('btn-upload-img')
我遇到了这个错误:
Failure/Error: raise ActionController::RoutingError, "No route matches [#{env['REQUEST_METHOD']}] #{env['PATH_INFO'].inspect}"
ActionController::RoutingError:
No route matches [GET] "/home/Anton-S/RubymineProjects/rails_projects/gallery/spec/support/uploads/image/image/8790/solnce-kosmos-merkuriy.jpg"
# /var/lib/gems/2.3.0/gems/railties-5.1.4/lib/rails/rack/logger.rb:36:in `call_app'
# /var/lib/gems/2.3.0/gems/railties-5.1.4/lib/rails/rack/logger.rb:24:in `block in call'
# /var/lib/gems/2.3.0/gems/railties-5.1.4/lib/rails/rack/logger.rb:24:in `call'
# /var/lib/gems/2.3.0/gems/rack-2.0.3/lib/rack/method_override.rb:22:in `call'
# /var/lib/gems/2.3.0/gems/rack-2.0.3/lib/rack/runtime.rb:22:in `call'
# /var/lib/gems/2.3.0/gems/rack-2.0.3/lib/rack/sendfile.rb:111:in `call'
# /var/lib/gems/2.3.0/gems/railties-5.1.4/lib/rails/engine.rb:522:in `call'
# /var/lib/gems/2.3.0/gems/rack-2.0.3/lib/rack/urlmap.rb:68:in `block in call'
# /var/lib/gems/2.3.0/gems/rack-2.0.3/lib/rack/urlmap.rb:53:in `each'
# /var/lib/gems/2.3.0/gems/rack-2.0.3/lib/rack/urlmap.rb:53:in `call'
# /var/lib/gems/2.3.0/gems/capybara-2.16.1/lib/capybara/server.rb:44:in `call'
# /var/lib/gems/2.3.0/gems/rack-2.0.3/lib/rack/handler/webrick.rb:86:in `service'
# ------------------
# --- Caused by: ---
# Capybara::CapybaraError:
# Your application server raised an error - It has been raised in your test code because Capybara.raise_server_errors == true
# /var/lib/gems/2.3.0/gems/capybara-2.16.1/lib/capybara/session.rb:145:in `raise_server_error!'
Finished in 17.15 seconds (files took 2.55 seconds to load)
133 examples, 1 failure
Failed examples:
rspec ./spec/features/images_spec.rb:20 # Images should allow a registered user to create image and go to it page
我检查过我确实有这个文件
/spec/fixtures/solnce-kosmos-merkuriy.jpg
在正确的地方。
这是我的/config/initializers/carrierwave.rb
if Rails.env.test? || Rails.env.cucumber?
CarrierWave.configure do |config|
config.storage = :file
config.enable_processing = false
end
# make sure our uploader is auto-loaded
ImageUploader
# use different dirs when testing
CarrierWave::Uploader::Base.descendants.each do |klass|
next if klass.anonymous?
klass.class_eval do
def cache_dir
"#{Rails.root}/spec/support/uploads/tmp"
end
def store_dir
"#{Rails.root}/spec/support/uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
end
end
end
我的rails_helper.rb
require 'support/factory_bot'
require 'spec_helper'
require 'shoulda/matchers'
require 'capybara/rspec'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
ActiveRecord::Migration.maintain_test_schema!
module DeviseRequestSpecHelpers
include Warden::Test::Helpers
def sign_in(resource_or_scope, resource = nil)
resource ||= resource_or_scope
scope = Devise::Mapping.find_scope!(resource_or_scope)
login_as(resource, scope: scope)
end
def sign_out(resource_or_scope)
scope = Devise::Mapping.find_scope!(resource_or_scope)
logout(scope)
end
end
RSpec.configure do |config|
Capybara.ignore_hidden_elements = false
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_spec_type_from_file_location!
config.filter_rails_from_backtrace!
config.include Devise::Test::ControllerHelpers, type: :controller
config.include DeviseRequestSpecHelpers, type: :request
end
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :rails
end
end
我的spec_helper.rb
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.shared_context_metadata_behavior = :apply_to_host_groups
end
此图片上传页面的 View 模板:
.row.main-new-image
= form_for @image, url: create_image_path, html: {multipart: true, method: :post, remote: true } do |form|
#new_image_error_explanation
.field
.p.text-center
%span.btn.btn-new-image{id: 'new-image-button'}
%p#p-new-image-button Choose image
\#{form.file_field :image, id: 'new-image-id'}
.field
= form.hidden_field :user_id, value: current_user.id
.actions
.p.text-center
= form.submit 'Upload', class: 'btn button-upload-img', id: 'btn-upload-img'
我所有其他的 Capybara 和 RSpec 测试都工作正常。
请帮助我了解此问题的原因以及如何解决和预防。
如果可以帮助解决这个问题,我可以提供更多信息。
UPDATE 1
阅读 Thomas Walpole 的评论后,我决定更新我的代码并尝试一些其他功能。我包括新 gem
gem 'database_cleaner'
我还添加了新代码来清除测试上传的代码。这里更新了 rails_helper.rb
require 'support/factory_bot'
require 'spec_helper'
require 'shoulda/matchers'
require 'capybara/rspec'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
ActiveRecord::Migration.maintain_test_schema!
module DeviseRequestSpecHelpers
include Warden::Test::Helpers
def sign_in(resource_or_scope, resource = nil)
resource ||= resource_or_scope
scope = Devise::Mapping.find_scope!(resource_or_scope)
login_as(resource, scope: scope)
end
def sign_out(resource_or_scope)
scope = Devise::Mapping.find_scope!(resource_or_scope)
logout(scope)
end
end
RSpec.configure do |config|
Capybara.javascript_driver = :selenium
Capybara.ignore_hidden_elements = true
Capybara.register_driver :selenium do |app|
Capybara::Selenium::Driver.new(app, browser: :firefox)
end
config.include Capybara::DSL
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.before(:suite) do
DatabaseCleaner.strategy = :transaction
DatabaseCleaner.clean_with(:truncation)
end
config.around(:each) do |example|
DatabaseCleaner.cleaning do
example.run
end
end
config.after(:all) do
if Rails.env.test?
FileUtils.rm_rf(Dir["#{Rails.root}/spec/support/uploads"])
end
end
config.infer_spec_type_from_file_location!
config.filter_rails_from_backtrace!
config.include Devise::Test::ControllerHelpers, type: :controller
config.include DeviseRequestSpecHelpers, type: :request
end
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :rails
end
end
这是我更新的测试
require 'rails_helper'
describe 'Images', type: :feature do
before(:each) do
@user = create(:user)
visit '/users/sign_in'
fill_in 'sing-in-email-input', with: @user.email
fill_in 'sign-in-password-input', with: @user.password
click_button 'btn-sign-in'
visit '/categories'
click_on 'btn-new-category'
have_current_path(new_category_path)
fill_in 'category_name', with: 'Test'
click_button 'btn-create category'
visit '/categories'
first('.fa', :visible => false).click
have_current_path(category_path(id: Category.last.slug.to_s))
end
#ISSUE WITH
it 'should allow a registered user to create image and go to it page', :driver => :selenium do
click_on 'btn-upload-images'
have_current_path(new_image_path(id: Category.last.slug.to_s))
attach_file('image[image]',
File.join(Rails.root, '/spec/fixtures/solnce-kosmos-merkuriy.jpg'), :visible => false)
click_on('btn-upload-img')
end
end
正如 Thomas Walpole 告诉我的那样,我检查了测试日志并看到了下一个(关于当前测试):
Started GET "/en/categories/test/new_image" for 127.0.0.1 at 2018-01-30 14:33:26 +0200
Processing by ImagesController#new as HTML
Parameters: {"locale"=>"en", "id"=>"test"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 22], ["LIMIT", 1]]
(0.2ms) SAVEPOINT active_record_2
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 22], ["LIMIT", 1]]
SQL (0.3ms) INSERT INTO "user_actions" ("user_id", "action_type", "url", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["user_id", 22], ["action_type", "navigation"], ["url", "http://127.0.0.1:38226/en/categories/test/new_image"], ["created_at", "2018-01-30 12:33:26.645909"], ["updated_at", "2018-01-30 12:33:26.645909"]]
(0.1ms) RELEASE SAVEPOINT active_record_2
Rendering images/new.html.haml within layouts/application
Rendered images/_form.html.haml (5.2ms)
Rendered images/new.html.haml within layouts/application (7.5ms)
Category Load (1.1ms) SELECT DISTINCT categories.*, COUNT(images.*) AS images_count, categories.*, COUNT(likes.*) AS likes_count, categories.*, COUNT(comments.*) AS comments_count FROM "categories" LEFT OUTER JOIN "images" ON "images"."category_id" = "categories"."id" LEFT OUTER JOIN "images" "images_categories_join" ON "images_categories_join"."category_id" = "categories"."id" LEFT OUTER JOIN "likes" ON "likes"."image_id" = "images_categories_join"."id" LEFT OUTER JOIN "images" "images_categories_join_2" ON "images_categories_join_2"."category_id" = "categories"."id" LEFT OUTER JOIN "comments" ON "comments"."image_id" = "images_categories_join_2"."id" GROUP BY categories.id ORDER BY images_count DESC, likes_count DESC, comments_count DESC LIMIT $1 [["LIMIT", 5]]
Rendered layouts/_header.html.haml (4.3ms)
Rendered layouts/_footer.haml (0.0ms)
Completed 200 OK in 21ms (Views: 12.6ms | ActiveRecord: 2.1ms)
Category Load (0.6ms) SELECT "categories".* FROM "categories" ORDER BY "categories"."id" DESC LIMIT $1 [["LIMIT", 1]]
Started POST "/en/categories/test/create_image" for 127.0.0.1 at 2018-01-30 14:33:26 +0200
Processing by ImagesController#create as JS
Parameters: {"utf8"=>"✓", "image"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x0000000ae4e008 @tempfile=#<Tempfile:/tmp/RackMultipart20180130-28977-1nptliu.jpg>, @original_filename="solnce-kosmos-merkuriy.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"image[image]\"; filename=\"solnce-kosmos-merkuriy.jpg\"\r\nContent-Type: image/jpeg\r\n">, "user_id"=>"22"}, "commit"=>"Upload", "locale"=>"en", "id"=>"test"}
Category Load (0.2ms) SELECT "categories".* FROM "categories" WHERE "categories"."slug" = $1 LIMIT $2 [["slug", "test"], ["LIMIT", 1]]
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 22], ["LIMIT", 1]]
(0.3ms) SAVEPOINT active_record_2
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 22], ["LIMIT", 1]]
Category Load (0.2ms) SELECT "categories".* FROM "categories" WHERE "categories"."id" = $1 LIMIT $2 [["id", 18], ["LIMIT", 1]]
SQL (0.4ms) INSERT INTO "images" ("image", "category_id", "created_at", "updated_at", "user_id") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["image", "solnce-kosmos-merkuriy.jpg"], ["category_id", 18], ["created_at", "2018-01-30 12:33:26.945577"], ["updated_at", "2018-01-30 12:33:26.945577"], ["user_id", 22]]
(0.2ms) RELEASE SAVEPOINT active_record_2
Redirected to http://127.0.0.1:38226/en/categories/test/12
Completed 200 OK in 22ms (ActiveRecord: 1.6ms)
Started GET "/en/categories/test/12" for 127.0.0.1 at 2018-01-30 14:33:26 +0200
Processing by ImagesController#show as HTML
Parameters: {"locale"=>"en", "id"=>"test", "image_id"=>"12"}
User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 22], ["LIMIT", 1]]
(0.1ms) SAVEPOINT active_record_2
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 22], ["LIMIT", 1]]
SQL (0.3ms) INSERT INTO "user_actions" ("user_id", "action_type", "url", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["user_id", 22], ["action_type", "navigation"], ["url", "http://127.0.0.1:38226/en/categories/test/12"], ["created_at", "2018-01-30 12:33:26.966397"], ["updated_at", "2018-01-30 12:33:26.966397"]]
(0.1ms) RELEASE SAVEPOINT active_record_2
Category Load (0.1ms) SELECT "categories".* FROM "categories" WHERE "categories"."slug" = $1 LIMIT $2 [["slug", "test"], ["LIMIT", 1]]
Image Load (0.2ms) SELECT "images".* FROM "images" WHERE "images"."category_id" = $1 AND "images"."id" = $2 LIMIT $3 [["category_id", 18], ["id", 12], ["LIMIT", 1]]
Like Load (0.2ms) SELECT "likes".* FROM "likes" WHERE "likes"."image_id" = $1 AND "likes"."user_id" = $2 LIMIT $3 [["image_id", 12], ["user_id", 22], ["LIMIT", 1]]
Rendering images/show.html.haml within layouts/application
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 22], ["LIMIT", 1]]
(0.3ms) SELECT COUNT(*) FROM "comments" WHERE "comments"."image_id" = $1 [["image_id", 12]]
Like Load (0.2ms) SELECT "likes".* FROM "likes" WHERE "likes"."user_id" = $1 AND "likes"."image_id" = 12 LIMIT $2 [["user_id", 22], ["LIMIT", 1]]
(0.3ms) SELECT COUNT(*) FROM "likes" WHERE "likes"."image_id" = $1 [["image_id", 12]]
Rendered likes/_like.html.haml (3.2ms)
Rendered likes/_like_form.html.haml (7.3ms)
Rendered comments/_comments.html.haml (2.7ms)
Rendered comments/_comments_container.html.haml (5.1ms)
Rendered images/show.html.haml within layouts/application (25.6ms)
Category Load (1.3ms) SELECT DISTINCT categories.*, COUNT(images.*) AS images_count, categories.*, COUNT(likes.*) AS likes_count, categories.*, COUNT(comments.*) AS comments_count FROM "categories" LEFT OUTER JOIN "images" ON "images"."category_id" = "categories"."id" LEFT OUTER JOIN "images" "images_categories_join" ON "images_categories_join"."category_id" = "categories"."id" LEFT OUTER JOIN "likes" ON "likes"."image_id" = "images_categories_join"."id" LEFT OUTER JOIN "images" "images_categories_join_2" ON "images_categories_join_2"."category_id" = "categories"."id" LEFT OUTER JOIN "comments" ON "comments"."image_id" = "images_categories_join_2"."id" GROUP BY categories.id ORDER BY images_count DESC, likes_count DESC, comments_count DESC LIMIT $1 [["LIMIT", 5]]
Rendered layouts/_header.html.haml (4.6ms)
Rendered layouts/_footer.haml (0.1ms)
Completed 200 OK in 43ms (Views: 30.0ms | ActiveRecord: 4.1ms)
Started GET "/home/Anton-S/RubymineProjects/rails_projects/gallery/spec/support/uploads/image/image/12/solnce-kosmos-merkuriy.jpg" for 127.0.0.1 at 2018-01-30 14:33:27 +0200
(0.2ms) ROLLBACK TO SAVEPOINT active_record_1
(0.1ms) ROLLBACK
(0.1ms) BEGIN
(0.1ms) COMMIT
(0.0ms) BEGIN
(0.0ms) SAVEPOINT active_record_1
(0.1ms) SAVEPOINT active_record_2
据我了解,图片已成功上传。但是我仍然得到这个错误
Failure/Error: raise ActionController::RoutingError, "No route matches [#{env['REQUEST_METHOD']}] #{env['PATH_INFO'].inspect}"
ActionController::RoutingError:
No route matches [GET] "/home/Anton-S/RubymineProjects/rails_projects/gallery/spec/support/uploads/image/image/12/solnce-kosmos-merkuriy.jpg"
UPDATE 2
不幸的是,我找到的唯一解决方案是设置/config/environments/test.rb
config.action_dispatch.show_exceptions = true
但我仍然认为有更好的解决方案。
最佳答案
因此,从日志中,我们可以看到文件正在成功上传。
问题是当显示页面呈现时,图像被添加到 HTML 中,其 URL 类似于 '/home/Anton-S/RubymineProjects/rails_projects/gallery/spec/support/uploads/image/image/12/solnce-kosmos-merkuriy.jpg' 这将不起作用,因为 Rails 应用程序不会响应应用程序根目录中 public
目录之外的随机文件。这样做将是一个巨大的安全问题。最简单的解决方案是将图像存储到 public
目录中,以便 Rails 应用程序将它们作为静态 Assets 提供。类似的东西
def cache_dir
"public/test/uploads/tmp"
end
def store_dir
"public/test/uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
注意:我还评论了您对 have_current_path
匹配器的使用。
关于ruby-on-rails - capybara 上传图片问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48499129/
我有一个文件字段,其中包含 opacity: 0并且正在重叠一个假按钮。它是一种常见的 css 技术,可以伪造一种在不同浏览器中一致显示的“上传按钮”。 Capybara 不允许我打电话 attach
我正在尝试为我的 ROR 应用程序编写一些 capybara cucumber 脚本,但发现很难通过每次都进行更改并运行完整功能来使脚本正确。 是否有适用于 Capybara 的 REPL(Read
像这样的html 我的代码是 attach_file("ok","./fileset/publisher/upload_pic.jpg") 但我失败了: 失败: Capybara::Element
我想在我的代码中设置不同的 Capybara 等待时间,具体取决于它们通常需要多长时间才能完全加载?我是否必须重复更改 Capybara.default_wait_time 还是有更好的方法? 最佳答
在 Capybara 中,是否可以在新窗口而不是当前窗口中打开链接? 最佳答案 如果此元素是链接,您只需获取其 href 并在新窗口中打开它: url = find('.some_link')[:hr
对于编辑记录的集成测试,我尝试用新文本替换表单输入字段中的现有文本: find("input[@id='course_title']").set("a safer workplace") 但是,每次我
我有一个动态生成的表单,如下所示: Do you like Pizza? [ ] Yes [ ] No HTML 看起来像这样: Do you like Pizza?
我正在尝试填写两个标有 id="admin_passsword"的文本框。我可以轻松访问第一个文本框,但由于除了占位符和上面的标签之外没有任何区别,我不知道如何访问第二个文本框来填写该字段。
我是一个新手,尝试使用 Capybara 测试我的 Rails 项目,但是当我尝试从我的 div 中检测一些字符串时,我对 page 和 page.body 的含义感到困惑:(in :js=>true
我在使用 rspec、capybara、capybara-webkit 和 timecop 的某些集成规范中看到错误。 Capybara::FrozenInTime: time appears
我使用以下 html 堆栈创建了自定义上传表单: 文件字段通过 display: none 的 css 隐藏属性(property)。因此,当她单击标签(自定义样式)时,用户会调用文件
假设我在 Mac OS X 上安装了 PhantomJS,我可以编写一个普通的旧 Ruby 脚本(没有 Cucumber,没有 RSpec)来驱动 Poltergeist 吗?换句话说,我想要一些 g
我希望单击我的测试应用程序上出现的弹出消息(如果存在)。我对 capybara 很陌生,似乎找不到办法做到这一点。我以前有过使用 watir 的经验,如果我使用 watir 的话,会是这样的: if
我目前使用 Watir-webdriver 进行所有前端测试,但开发团队使用 Capybara 在 Jenkins CI 上运行测试。我们都使用相同的 Cucumber 功能。 值得我们进行两次有效的
Capybara的API似乎不支持配置HTTP代理。有没有什么方法可以和它一起使用? 上下文:我使用 capybara 和 cucumber 来测试 Rails 应用程序,并使用 akephalos
我很好奇是否有更好的方法来测试页面中是否存在完整的 URL(包括协议(protocol))。 使用 Capybara 2.10.2 和 Rails 5.0.0.1,我有以下设置: rails_help
我有以下测试: it 'shows the current quantity of items inside cart' do item = create(:item) visit
我正在使用 Capybara 自动截取一些屏幕截图。 我需要 chrome 浏览器最大化运行,但我似乎无法让它工作。 基于 https://sites.google.com/a/chromium.or
下面是两个单选按钮的 html 代码,它们只是“值”属性不同 我想做的是选择“value =2”的单选按钮 我尝试使用“选择(“AmountOption”)”选择第一个单选按钮,但我想选择第二个单
我尝试使用几种变体来检查 Capybara 的 200 Ok HTTP 响应,但没有一个变体不起作用: response.should be_success page.status.should be
我是一名优秀的程序员,十分优秀!