#selenium-chromedriver #capybara #minitest #ruby-on-rails-6.1 #load-path
Вопрос:
(Из главы 14 в «Гибкой веб-разработке с Rails 6») Я пытаюсь запустить системный тест, который касается модели, для которой требуется файл из каталога /lib. Файл загружается нормально, и код отлично работает на локальном хосте в режиме разработки, но как только я запускаю тест, он выдает ошибки с:
Error: OrdersTest#test_visiting_the_index: DRb::DRbRemoteError: cannot load such file -- pago (LoadError) app/models/order.rb:1:in `lt;maingt;'
Выдержка из модели order.rb
, для которой требуется файл , является:
require "pago" class Order lt; ApplicationRecord enum pay_type: { "Cheque" =gt; 0, "Credit card" =gt; 1, "Purchase order" =gt; 2 } has_many :line_items, dependent: :destroy validates :name, :address, :email, presence: true validates :pay_type, inclusion: pay_types.keys def add_line_items_from_cart(cart) cart.line_items.each do |item| item.cart_id = nil line_items lt;lt; item end end def charge!(pay_type_params) payment_details = {} payment_method = nil case pay_type when "Cheque" payment_method = :cheque payment_details[:routing] = pay_type_params[:routing_number] payment_details[:account] = pay_type_params[:account_number] when "Credit card" payment_method = :credit_card month,year = pay_type_params[:expiration_date].split(//) payment_details[:cc_num] = pay_type_params[:credit_card_number] payment_details[:expiration_month] = month payment_details[:expiration_year] = year when "Purchase order" payment_method = :po payment_details[:po_num] = pay_type_params[:po_number] end payment_result = Pago.make_payment( order_id: id, payment_method: payment_method, payment_details: payment_details ) if payment_result.succeeded? OrderMailer.received(self).deliver_later else raise payment_result.error end end end
Выдержка из фактического /lib/pago.rb
:
require "ostruct" class Pago def self.make_payment(order_id:, payment_method:, payment_details:) case payment_method when :cheque Rails.logger.info "Processing cheque: " payment_details.fetch(:routing).to_s "/" payment_details.fetch(:account).to_s when :credit_card Rails.logger.info "Processing credit_card: " payment_details.fetch(:cc_num).to_s "/" payment_details.fetch(:expiration_month).to_s "/" payment_details.fetch(:expiration_year).to_s when :po Rails.logger.info "Processing purchase order: " payment_details.fetch(:po_num).to_s else raise "Unknown payment_method #{payment_method}" end sleep 3 unless Rails.env.test? Rails.logger.info "Done Processing Payment" OpenStruct.new(succeeded?: true) end end
The test file that I’, trying to run: test/system/orders_test.rb
require "application_system_test_case" class OrdersTest lt; ApplicationSystemTestCase include ActiveJob::TestHelper setup do @order = orders(:one) end test "visiting the index" do visit orders_url assert_selector "h1", text: "Orders" end test "destroying an Order" do visit orders_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Order was successfully destroyed" end test "check full payment with cheque flow" do LineItem.delete_all Order.delete_all visit store_index_url click_on 'Add to cart', match: :first click_on 'Checkout' fill_in 'order_name', with: 'Dave Thomas' fill_in 'order_address', with: '123 Main Street' fill_in 'order_email', with: 'dave@example.com' assert_no_selector "#order_routing_number" select 'Cheque', from: 'Pay type' fill_in 'Routing #', with: '123456' fill_in 'Account #', with: '678901' assert_selector "#order_routing_number" assert_selector "#order_account_number" perform_enqueued_jobs { click_button 'Place order' } orders = Order.all assert_equal 1, orders.size order = orders.first assert_equal 'Dave Thomas', order.name assert_equal '123 Main Street', order.address assert_equal 'dave@example.com', order.email assert_equal 'Cheque', order.pay_type assert_equal 1, order.line_items.size mail = ActionMailer::Base.deliveries.last assert_equal ['dave@example.com'], mail.to assert_equal 'James Kemplt;from@example.comgt;', mail[:from].value assert_equal 'Order received; thanks', mail.subject end test "check CC number for credit card payment choice" do visit store_index_url click_on 'Add to cart', match: :first click_on 'Checkout' fill_in 'order_name', with: 'Dave Thomas' fill_in 'order_address', with: '123 Main Street' fill_in 'order_email', with: 'dave@example.com' assert_no_selector "#order_credit_card_number" assert_no_selector "#order_expiration_date" select 'Credit card', from: 'Pay type' assert_selector "#order_credit_card_number" assert_selector "#order_expiration_date" end test "check PO number for purchase order payment choice" do visit store_index_url click_on 'Add to cart', match: :first click_on 'Checkout' fill_in 'order_name', with: 'Dave Thomas' fill_in 'order_address', with: '123 Main Street' fill_in 'order_email', with: 'dave@example.com' assert_no_selector "#order_po_number" select 'Purchase order', from: 'Pay type' assert_selector "#order_po_number" end end
Если я запущу консоль rails require 'pago'
, она вернет значение true. Я не вижу никаких подсказок в различных файлах конфигурации и среды относительно того, в чем может быть проблема. Код учебника, похоже, такой же, как и у меня. Я просто не могу понять, что здесь не так. Кто-нибудь может помочь?
Мой файл Gemfile К вашему сведению (у меня установлен пакет):
source 'https://rubygems.org' git_source(:github) { |repo| "https://github.com/#{repo}.git" } ruby '3.0.2' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails', branch: 'main' gem 'rails', '~gt; 6.1.4', 'gt;= 6.1.4.1' # Use sqlite3 as the database for Active Record gem 'sqlite3', '~gt; 1.4' # Use Puma as the app server gem 'puma', '~gt; 5.0' # Use SCSS for stylesheets gem 'sass-rails', 'gt;= 6' # Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker gem 'webpacker', '~gt; 5.0' # Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks gem 'turbolinks', '~gt; 5' # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder gem 'jbuilder', '~gt; 2.7' # Use Redis adapter to run Action Cable in production # gem 'redis', '~gt; 4.0' # Use Active Model has_secure_password # gem 'bcrypt', '~gt; 3.1.7' # Use Active Storage variant # gem 'image_processing', '~gt; 1.2' # Reduces boot times through caching; required in config/boot.rb gem 'bootsnap', 'gt;= 1.4.4', require: false group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] end group :development do # Access an interactive console on exception pages or by calling 'console' anywhere in the code. gem 'web-console', 'gt;= 4.1.0' # Display performance information such as SQL time and flame graphs for each request in your browser. # Can be configured to work on production as well see: https://github.com/MiniProfiler/rack-mini-profiler/blob/master/README.md gem 'rack-mini-profiler', '~gt; 2.0' gem 'listen', '~gt; 3.3' # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring' end group :test do # Adds support for Capybara system testing and selenium driver gem 'capybara', 'gt;= 3.26' gem 'selenium-webdriver' # Easy installation and use of web drivers to run system tests with browsers gem 'webdrivers' end # Windows does not include zoneinfo files, so bundle the tzinfo-data gem gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
Комментарии:
1. Какую команду вы используете для запуска теста?
2.
bin/rails test test/system/orders_test.rb
3. Сегодня я вернулся к своему коду без каких-либо изменений в кодовой базе, единственное, что я сделал, это выключил и перезагрузил локальную машину, чтобы эта ошибка исчезла. Таким образом, включение и выключение компьютера решило эту проблему! Есть какие-либо предположения относительно того, что могло измениться, чтобы устранить эту ошибку? Возможно, что-то с точки зрения окружающей среды, что было сброшено?