我正在尝试为使用Sinatra构建的REST API构建单元测试。目前,我只想测试我的回显功能是否正常工作。Echo使用POST并将从该POST返回完全相同的有效负载。由于我在ruby方面还很新,所以请原谅我如果我没有使用适当的术语。
这是我要测试的代码:
post '/echo' do
request.body.read
end
这是我正在尝试制作的单元测试:
ENV['RACK_ENV'] = 'test'
require './rest_server'
require 'test/unit'
require 'rack/test'
require 'json'
class RestServer < Test::Unit::TestCase
def app
Sinatra::Application
end
def test_check_methods
data = '{"dataIn": "hello"}'
response = post '/echo', JSON.parse(data)
assert.last_response.ok?
assert(response.body == data)
end
end
使用上述代码后,这是出现的错误:
NoMethodError: undefined method `dataIn' for Sinatra::Application:Class
/Users/barrywilliams/.rvm/gems/ruby-1.9.3-p448/gems/sinatra-1.3.4/lib/sinatra/base.rb:1285:in `block in compile!'
/Users/barrywilliams/.rvm/gems/ruby-1.9.3-p448/gems/sinatra-1.3.4/lib/sinatra/base.rb:1285:in `each_pair'
/Users/barrywilliams/.rvm/gems/ruby-1.9.3-p448/gems/sinatra-1.3.4/lib/sinatra/base.rb:1285:in `compile!'
/Users/barrywilliams/.rvm/gems/ruby-1.9.3-p448/gems/sinatra-1.3.4/lib/sinatra/base.rb:1267:in `route'
/Users/barrywilliams/.rvm/gems/ruby-1.9.3-p448/gems/sinatra-1.3.4/lib/sinatra/base.rb:1256:in `post'
/Users/barrywilliams/.rvm/gems/ruby-1.9.3-p448/gems/sinatra-1.3.4/lib/sinatra/base.rb:1688:in `block (2 levels) in delegate'
/Users/barrywilliams/RubymineProjects/project/rest_server_test.rb:20:in `test_check_methods'
如果我不使用
JSON.parse
尝试执行它,我会得到NoMethodError: undefined method `key?' for "{\"dataIn\": \"hello\"}":String
/Users/barrywilliams/.rvm/gems/ruby-1.9.3-p448/gems/sinatra-1.3.4/lib/sinatra/base.rb:1265:in `route'
/Users/barrywilliams/.rvm/gems/ruby-1.9.3-p448/gems/sinatra-1.3.4/lib/sinatra/base.rb:1256:in `post'
/Users/barrywilliams/.rvm/gems/ruby-1.9.3-p448/gems/sinatra-1.3.4/lib/sinatra/base.rb:1688:in `block (2 levels) in delegate'
/Users/barrywilliams/RubymineProjects/project/rest_server_test.rb:20:in `test_check_methods'
如果我尝试使用
data = 'hello'
,那么我会得到相同的错误信息 undefined method 'key?'
。我尝试了这个建议,但没有成功: http://softwareblog.morlok.net/2010/12/18/testing-post-with-racktest/ 我收到一个错误消息,说
post
只接受 2 个参数,而不是 3 个。因此,总结一下,我需要能够发起调用,让我正在测试的代码接收调用并返回响应,然后我需要能够读取该响应并验证它是否为原始数据。目前看来,它似乎只停留在发起调用阶段。
post 'echo',{"dataIn" => "hello"}
- Lars Haugseth