ruby-on-rails – rspec,factory_girl和datamapper的Spork和cache_classes问题

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – rspec,factory_girl和datamapper的Spork和cache_classes问题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个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这样的东西,当cache为真时:

Spork.each_run do
    Dir.glob("#{Rails.root}/app/models/*.rb").sort.each { |file| load file }
end

但我不喜欢这个解决方案.

解决方法

只需添加
ActiveSupport::Dependencies.clear

到prefork块的末尾.这将照顾清理模型.

此外,您希望将rspec配置包含到Spork.each_run中,同样需要规范支持和共享文件.

这个工作,我使用这个设置在2个项目没有任何麻烦.

猜你在找的Ruby相关文章