我遇到了Spork测试服务器的问题。
如果我在config / environments / test.rb中设置config.cache_classes = false,那么规格就会开始出现rasie错误。
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时,一切都运行良好,但它没有重新加载模型,控制器类,所以在这种情况下我没有看到使用spork的重点。
当缓存为真时,我尝试添加到spec_helper.rb这样的东西:
Spork.each_run do
Dir.glob("#{Rails.root}/app/models/*.rb").sort.each { |file| load file }
end
但我不喜欢这个解决方案。
答案 0 :(得分:20)
只需添加:
ActiveSupport::Dependencies.clear
到prefork块的末尾。这将负责清理模型。
此外,您希望将rspec配置包含移动到Spork.each_run,同样需要规范支持和共享文件。
这很有效,我在2个项目中使用此设置,没有任何麻烦。
答案 1 :(得分:8)
除了在config.cache_classes = false
中设置config/environments/test.rb
之外,以下内容似乎使DataMapper和Spork在我们的团队中发挥出色:
Spork.each_run do
# Routes
MyApp::Application.reload_routes!
if Spork.using_spork?
# Reload all app files
ActionDispatch::Reloader.cleanup!
ActionDispatch::Reloader.prepare!
# All factories
FactoryGirl.reload
end
end
答案 2 :(得分:0)
您好,我想分享一下帮助我再次进行测试的原因
事实证明,我必须添加shared_connection
技巧,因为spork抱怨连接丢失
在此之后,我不得不在块的末尾移动dependency.clear
线,因为它正在缓存我的模型。
Spork.each_run do
# ActiveSupport::Dependencies.clear # <-- moved this line at end of block as suggested by @solnic
ActiveRecord::Base.instantiate_observers
MyApp::Application.reload_routes!
FactoryGirl.reload
class ActiveRecord::Base
mattr_accessor :shared_connection
@@shared_connection = nil
def self.connection
@@shared_connection || retrieve_connection
end
end
ActiveRecord::Base.shared_connection = ActiveRecord::Base.connection
ActiveSupport::Dependencies.clear # <-- line moved here
end if Spork.using_spork?