Spork:如何刷新validation和其他代码?

我整天都在使用spork,大部分时间它都非常棒。

但是,我经常遇到一些问题,我需要重新启动Spork以便我的测试通过……现在我想知道它是否比它的价值更麻烦。 我是ruby的新手,所以有时我无法预测错误是由于刷新问题,还是因为我不熟悉Ruby和Rails而导致错误。

我需要将什么内容放入Spork.each_run块以便我的validation和其他内容刷新,以便我不必重新启动spork服务器?

谢谢

更新类时使用Guard重新加载Spork Guard :: Spork允许自动智能地启动/重新加载RSpec / Cucumber Spork服务器。

  1. https://github.com/guard/guard-spork
  2. http://flux88.com/2011/04/using-guard-spork-with-mongoid-devise/

编辑:如果你可以升级到Ruby 2.0,这是你最好的选择。 它足够快,并且可以让您以常规方式工作,而无需像Spork,Zeus等工具。 从本质上讲,你不需要我在下面写的任何东西。

如果您在开发时仍需要一些减速带,请查看快速路径命令 。


好吧,如果您更改了环境,初始化程序或spec_helper文件(并且保护spork是完美的),您想要重新加载Spork,但是当您更新其中一个类(模型)时不会,因为这会否定spork等工具的用途。 我有同样的问题:我可以删除模型中的所有方法,测试仍然会通过,因为Spork在内存中保存“旧”模型类。 需要重新启动Spork。

原因:

一些插件会导致模型代码被预加载,因此需要一些工作来阻止模型代码的发生。

您希望阻止预加载的模型代码,因为如果您进行任何更改(例如validation),这将不会“重新加载”它们。

解决方案:

取决于所涉及的gem。 在我的情况下,我不得不处理Devise和FactoryGirl,但实质上,你是通过使用Wiki上描述的Spork.trap_method来实现的: https : //github.com/sporkrb/spork/wiki/Spork.trap_method-Jujitsu

此外,您可以运行spork -d来获取预加载的文件列表,跟踪导致此问题的gem可能会有所帮助。

示例:Rails 3.0.x + Rspec2 + Spork 0.9.0.rcX + Capybara + Devise + FactoryGirl

 # spec/spec_helper.rb Spork.prefork do # This file is copied to spec/ when you run 'rails generate rspec:install' ENV["RAILS_ENV"] ||= 'test' require File.expand_path("../../config/environment", __FILE__) require 'rspec/rails' require 'capybara/rspec' require 'capybara/rails' # set "gem 'factory_girl', :require => false" in Gemfile require 'factory_girl' # deal with Devise require "rails/application" Spork.trap_method(Rails::Application, :reload_routes!) require File.dirname(__FILE__) + "/../config/environment.rb" Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f} RSpec.configure do |config| config.mock_with :rspec config.use_transactional_fixtures = false config.before(:suite) do DatabaseCleaner.strategy = :transaction end config.before(:each) do DatabaseCleaner.start end config.after(:each) do DatabaseCleaner.clean end # Devise controller test helpers: config.include Devise::TestHelpers, :type => :controller end end Spork.each_run do # deal with factory girl Factory.definition_file_paths = [File.join(Rails.root, 'spec', 'factories')] Factory.find_definitions end 

请注意,在测试环境中需要将config.cache_classes = true设置为true ,否则您可能会从FactoryGirl等gem中获得错误。

这使我的模型测试(规范)快速运行,并在每次保存文件并激活rspec时“重新加载”它们。

编辑:如果您在Ruby 1.9.3上运行,您可以尝试一个有趣的替代方案:Zeus – https://github.com/burke/zeus

来自http://www.rubyinside.com/how-to-rails-3-and-rspec-2-4336.html?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+RubyInside+%28Ruby+Inside%29 :

尽管如此,还是会留下一点小麻烦。 如果更新app / models / person.rb,则更改将不会在测试中生效,因为Spork的旧Person仍在内存中。 解决此问题的一种方法是编辑config / environments / test.rb并更改:

 config.cache_classes = true 

至:

 config.cache_classes = false 

使用更新版本的Factory Girl,您无需做太多工作。 首先,在FactoryGirl.reload中添加Spork.each_run 。 如果你有带class参数的工厂,它们应该是字符串。

factory :my_model, class: 'MyModel' do...

代替

factory :my_model, class: MyModel do...