在测试的时候,要运行 RAILS_ENV=test rake sunspot:solr:start 来启动 8981 端口的 solr 引擎,有没有什么方法,能做到不用手动去启动服务器,由测试中的代码来控制开关,而且只在想用到 sunspot 的测试文件中启动。
module TestSunspot class << self attr_accessor :pid, :original_session, :stub_session, :server def setup TestSunspot.original_session = Sunspot.session Sunspot.session = TestSunspot.stub_session = Sunspot::Rails::StubSessionProxy.new(Sunspot.session) end end def self.included(klass) klass.instance_eval do def startup Sunspot.session = TestSunspot.original_session rd, wr = IO.pipe pid = fork do STDOUT.reopen(wr) STDERR.reopen(wr) TestSunspot.server ||= Sunspot::Rails::Server.new begin TestSunspot.server.run ensure wr.close end end TestSunspot.pid = pid ready = false until ready do ready = true if rd.gets =~ /Started\ SocketConnector/ sleep 0.5 end rd.close end def shutdown Sunspot.remove_all! Process.kill("HUP",TestSunspot.pid) Process.wait Sunspot.session = TestSunspot.stub_session end end def teardown Sunspot.remove_all! end end end
参考: http://timcowlishaw.co.uk/post/3179661158/testing-sunspot-with-test-unit
#1 楼 @xds2000 你好,这个我看到了,也试着用了。才疏学浅,没弄明白。。依然还是要手动启动服务器。能再具体一点么?
@davidqhr 我也没测试上面的代码,不过 include 到你需要测试 test case 里面跑跑看。
gem "sunspot-rails-tester"