我有一些集成测试会间歇性地失败,总是出现
ActiveRecord::RecordNotFound
错误。 错误发生在控制器内,在给定固件ID的情况下进行了一个find
调用。虽然它在多个控制器中都会出现,但我在浏览站点时从未看到过这种行为,但我会说测试会在30-50%的时间内失败。重新运行测试似乎可以解决问题。
如果我手动将固件加载到开发数据库中,则似乎找不到的ID确实存在于表中。
我还没有找到许多关于遇到相同问题的人的信息...有什么想法吗?
更新:以下是test_helper.rb的内容
ENV["RAILS_ENV"] = "test"
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require 'capybara/rails'
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order.
#
# Note: You'll currently still have to declare fixtures explicitly in integration tests
# -- they do not yet inherit this setting
fixtures :all
# Add more helper methods to be used by all tests here...
end
# Transactional fixtures do not work with Selenium tests, because Capybara
# uses a separate server thread, which the transactions would be hidden
# from. We hence use DatabaseCleaner to truncate our test database.
DatabaseCleaner.strategy = :truncation
class ActionDispatch::IntegrationTest
# Make the Capybara DSL available in all integration tests
include Capybara::DSL
# Make the Capybara Email DSL available in all integration tests
include Capybara::Email::DSL
# Stop ActiveRecord from wrapping tests in transactions
self.use_transactional_fixtures = false
# Switch to selenium as the default driver for JS support
Capybara.default_driver = :selenium
# Only click on visible links!
Capybara.ignore_hidden_elements = true
teardown do
DatabaseCleaner.clean # Truncate the database
Capybara.reset_sessions! # Forget the (simulated) browser state
Capybara.use_default_driver # Revert Capybara.current_driver to Capybara.default_driver
end
end
更新以下是连续运行相同测试5次的结果。我运行了这些测试,等待它们完成,然后立即使用命令rails test:integration
再次运行它们。注意:在测试中始终存在的E和F实际上是测试错误-我正在修复这些错误。例如,第二个测试运行是“正确”的,但第一个显示了虚假的错误。
..E......E..........F.
.........E..........F.
..E......E..........F.
..E......E..........F.
..E....E.E..........F.
错误确实发生在两个不同的表中--它们并不试图查找相同的记录。但似乎只有一部分测试存在这个问题...
更新 这是测试结果中实际错误的样子:
1) Error:
test_browsing_user_snops(BrowseStoriesTest):
ActiveRecord::RecordNotFound: Couldn't find User with id=980190962
/home/myuser/.rvm/gems/ruby-1.9.3-p286/gems/activerecord-3.2.9/lib/active_record/relation/finder_methods.rb:341:in `find_one'
/home/myuser/.rvm/gems/ruby-1.9.3-p286/gems/activerecord-3.2.9/lib/active_record/relation/finder_methods.rb:312:in `find_with_ids'
/home/myuser/.rvm/gems/ruby-1.9.3-p286/gems/activerecord-3.2.9/lib/active_record/relation/finder_methods.rb:107:in `find'
/home/myuser/.rvm/gems/ruby-1.9.3-p286/gems/activerecord-3.2.9/lib/active_record/querying.rb:5:in `find'
/home/myuser/Projects/myproject/app/controllers/users_controller.rb:18:in `show'
...
请注意,当控制器尝试查找记录时,错误会出现。相关的代码行实际上是@user = User.find(params[:id])
。这种情况也会发生在其他模型中,不仅仅是用户控制器和用户模型。
fixtures:all
,每个文本中的固定装置都是可用的,但我可能错了。我只是通过像amodel(:one)
这样做来在集成测试中访问它们,其中amodel
在固定装置文件夹中有一个相应的amodel.yml
文件。理论上我可以切换到MySQL或PostgreSQL。现在只是开发而已。PostgreSQL比MySQL更好的特别原因吗?当我开始学习Rails时,我读到的东西推荐使用MySQL作为默认值。 - aardvarkk