Ben*_*aum 8 ruby rspec capybara tsung
我正在编写一个库,以一种可以被rails应用程序更好地使用的方式来包装tsung的功能.我想写一些归结为以下内容的集成测试:
对于第1步,虽然我可以在外部启动一个vanilla rails应用程序(例如%x{rails s}),但我很确定有一种更好的方法可以以编程方式创建一个适合测试的简单Web服务器.
tl; dr - 在测试中以编程方式启动简单Web服务器的方法是什么?
Thi*_*ilo 10
您可以滚动自己的简单服务器.这是一个使用thin和rspec的快速示例(必须安装那些gems,加上机架):
# spec/support/test_server.rb
require 'rubygems'
require 'rack'
module MyApp
module Test
class Server
def call(env)
@root = File.expand_path(File.dirname(__FILE__))
path = Rack::Utils.unescape(env['PATH_INFO'])
path += 'index.html' if path == '/'
file = @root + "#{path}"
params = Rack::Utils.parse_nested_query(env['QUERY_STRING'])
if File.exists?(file)
[ 200, {"Content-Type" => "text/html"}, File.read(file) ]
else
[ 404, {'Content-Type' => 'text/plain'}, 'file not found' ]
end
end
end
end
end
Run Code Online (Sandbox Code Playgroud)
然后在你的spec_helper:
# Include all files under spec/support
Dir["./spec/support/**/*.rb"].each {|f| require f}
# Start a local rack server to serve up test pages.
@server_thread = Thread.new do
Rack::Handler::Thin.run MyApp::Test::Server.new, :Port => 9292
end
sleep(1) # wait a sec for the server to be booted
Run Code Online (Sandbox Code Playgroud)
这将为您存储在spec/support目录中的任何文件提供服务.包括自己.对于所有其他请求,它将返回404.
这基本上就像上一个答案中提到的水豚所做的那样,减去了很多复杂性.
capybara使用临时的Rack服务器为其规格:
可以使用此系统为任何Rack应用程序(包括Rails应用程序)提供服务,尽管Rails配置可能会有些棘手。
| 归档时间: |
|
| 查看次数: |
4594 次 |
| 最近记录: |