我在使用 Spork 测试服务器时遇到了问题。
如果我在 config/environments/test.rb 中设置 config.cache_classes = false 则规范开始出现错误。
Failure/Error: task = Factory(:something, :foo => @foo, :bar => @bar)
DataMapper::ImmutableError:
Immutable resource cannot be modified
这是我的 spec_helper.rb:
require 'spork'
Spork.prefork do
if ENV['CODE_COVERAGE'] == '1'
require 'simplecov'
SimpleCov.start 'rails'
end
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'webmock/rspec'
require 'factory_girl'
Dir[Rails.root.join("spec/controllers/shared/*.rb")].each { |f| require f }
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
RSpec.configure do |config|
config.mock_with :mocha
config.include Rails.application.routes.url_helpers
config.include UrlHelper
config.before(:each) do
repository(:default) do
transaction = DataMapper::Transaction.new(repository)
transaction.begin
repository.adapter.push_transaction(transaction)
end
end
config.after(:each) do
repository(:default).adapter.pop_transaction.try(:rollback)
end
end
end
# This code will be run each time you run your specs.
Spork.each_run do
# reload factories
Factory.definition_file_paths = Dir[File.join(Rails.root, "spec", "factories")]
Factory.find_definitions
DatabaseCleaner.strategy = :truncation
DatabaseCleaner.clean
LoggedEvent.all.destroy!
end
当我有 config.cache_classes = true 时,一切正常,但它不会重新加载我的模型、 Controller 类,所以在这种情况下我没有看到使用 spork 的意义。
当缓存为真时,我尝试向 spec_helper.rb 添加类似这样的内容:
Spork.each_run do
Dir.glob("#{Rails.root}/app/models/*.rb").sort.each { |file| load file }
end
但我不喜欢这个解决方案。
最佳答案
只需添加:
ActiveSupport::Dependencies.clear
到 prefork block 的末尾。这将负责清除模型。
此外,您希望将 rspec 配置包含移动到 Spork.each_run,同样需要规范支持和共享文件。
这行得通,我在 2 个项目中使用此设置,没有任何麻烦。
关于ruby-on-rails - rspec、factory_girl 和 datamapper 的 Spork 和 cache_classes 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5913255/