【发布时间】:2013-08-26 17:15:38
【问题描述】:
我正在尝试为使用 Sinatra 构建的 REST API 构建单元测试。现在我只想测试我的回声功能是否正常工作。 Echo 使用 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 个。
因此,总而言之,我需要能够进行调用,让我正在测试的代码接收调用并返回响应,然后我需要能够读取该响应并验证它是原始数据.现在看起来它只是在拨打电话时遇到了困难。
【问题讨论】:
-
我认为您应该为此进行集成测试而不是单元测试。单元测试用于测试类而不是测试请求。也许这个问题会有所帮助? stackoverflow.com/questions/8013770/…
-
您是否尝试过仅发布数据结构?
post 'echo', {"dataIn" => "hello"}
标签: ruby unit-testing sinatra rack-test