2013-02-23 2 views
0

Я пытаюсь проверить приложение Голиаф + виноградный вроде следующего:Тестирование Голиаф + Grape с Rspec

require 'em-synchrony/em-mongo' 
require 'yajl/json_gem' 
require 'goliath' 
require 'grape' 

class API < Grape::API 
    version 'v1', :using => :path 
    format :json 

    resource 'categories' do 
    # http://0.0.0.0:9000/v1/categories/ 
    get "/" do 
     coll = env.mongo.collection('categories') #Connection Pool from Goliath ENV 
     coll.find({}) 
    end 
    end 
end 

class App < Goliath::API 
    def response(env) 
    API.call(env) 
    end 
end 

эти два класса находятся в одном файле под названием app.rb. Запуск ruby ./app.rb -sv запустил приложение goliath на http://0.0.0.0:9000/v1/categories/, которое отлично работает, но требует rspec перед тем, как создавать более сложные конечные точки. Во всяком случае запуска спецификации я получаю

неопределенными локальная переменная или метод `приложение»

, который я не могу избавиться:

$ bundle exec rspec spec/api_spec.rb 
FFFF 

Failures: 

    1) App App GET /v1/categories get several categories of repositories by name 
    Failure/Error: get "/v1/categories" 
    NameError: 
     undefined local variable or method `app' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1::Nested_1:0x993eec4> 
    # ./spec/api_spec.rb:9:in `block (4 levels) in <top (required)>' 

api_spec выглядит следующим образом:

require 'spec_helper' 

describe App do 
    include Rack::Test::Methods 

    describe App do 
    describe 'GET /v1/categories' do 
     it 'get several categories of repositories by name' do 
     get "/v1/categories" 
     last_response.status.should == 200 
     JSON.parse(last_response.body)["name"].should == "Ruby Web Frameworks" 
     end 
    end 
    end 
end 

UPDATE:

добавив метод приложение к спецификации/api_spec.rb:

def app 
    App 
end 

нарастания другой вид ошибки:

1) App App GET /v1/categories get several categories of repositories by name 
    Failure/Error: get "/v1/categories" 
    NoMethodError: 
     undefined method `call' for App:Class 
    # ./spec/api_spec.rb:13:in `block (4 levels) in <top (required)>' 

UPDATE

добавления класса API вызывается из метода приложения в спецификации/api_spec. rb:

def app 
    API 
end 

получить undefined method mongo'`:

Failures: 

    1) App App GET /v1/categories get several categories of repositories by name 
    Failure/Error: get "/v1/categories" 
    NoMethodError: 
     undefined method `mongo' for #<Hash:0xad5ea58> 
    # ./app.rb:14:in `block (2 levels) in <class:API>' 
    # ./spec/api_spec.rb:13:in `block (4 levels) in <top (required)>' 

см coll = env.mongo.collection('categories') внутри класса API

ответ

3

Я, наконец, смог заставить его работать, используя goliath test_helper. Это для отслеживания цели, надеясь, что это может помочь кому-то другому.

В spec/spec_helper.rb добавить goliath test helper и все зависимости. В моем случае:

require 'em-synchrony/em-http' 
require 'goliath/test_helper' 
require 'yajl/json_gem' 

Goliath.env = :test 

RSpec.configure do |c| 
    c.include Goliath::TestHelper, :example_group => { 
    :file_path => /spec\// 
    } 
end 

в spec/app_spec.гь

require 'spec_helper' 
require File.join(File.dirname(__FILE__), '../', 'app') 

describe App do 
    def config_file 
    File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'app.rb')) 
    end 

    let(:api_options) { { :config => config_file } } 

    it 'renders ' do 
    with_api(App, api_options) do 
     get_request(:path => '/v1/categories') do |c| 
     resp = JSON.parse(c.response) 
     categories = resp.map{|r|r['name']} 
     categories.to_s.should =~ /Ruby Web Frameworks/ 
     end 
    end 
    end 
end 

Голиаф приложение реж дерева, выглядит следующим образом:

[email protected]:~/rails/github/GGM$ ls -l 
total 48 
-rw-rw-r-- 1 lsoave lsoave 483 Feb 25 23:06 app.rb 
-rw-rw-r-- 1 lsoave lsoave 6321 Feb 25 23:06 categories.json 
drwxrwxr-x 2 lsoave lsoave 4096 Feb 25 23:06 config 
-rw-rw-r-- 1 lsoave lsoave 381 Feb 25 23:06 Gemfile 
-rw-rw-r-- 1 lsoave lsoave 2293 Feb 25 23:06 Gemfile.lock 
-rw-rw-r-- 1 lsoave lsoave 59 Feb 21 20:37 Procfile 
-rw-rw-r-- 1 lsoave lsoave 123 Feb 25 23:06 Rakefile 
-rw-rw-r-- 1 lsoave lsoave 7003 Feb 21 20:37 README.md 
-rw-rw-r-- 1 lsoave lsoave 238 Feb 25 23:06 README.mongoimport 
drwxrwxr-x 2 lsoave lsoave 4096 Feb 25 23:23 spec 
[email protected]:~/rails/github/GGM$ 

где конфигурации и спецификации SUBDIRS выглядеть следующим образом:

[email protected]:~/rails/github/GGM$ ls -l config spec 
config: 
total 4 
-rw-rw-r-- 1 lsoave lsoave 870 Feb 25 23:06 app.rb 

spec: 
total 11 
-rw-rw-r-- 1 lsoave lsoave 777 Feb 25 23:06 app_spec.rb 
-rw-rw-r-- 1 lsoave lsoave 218 Feb 25 23:06 spec_helper.rb 
[email protected]:~/rails/github/GGM$ 

основной Голиаф приложение является такой же, как мой первый пост:

require 'em-synchrony/em-mongo' 
require 'yajl/json_gem' 
require 'goliath' 
require 'grape' 

class API < Grape::API 
    version 'v1', :using => :path 
    format :json 

    resource 'categories' do 
    # http://0.0.0.0:9000/v1/categories/ 
    get "/" do 
     coll = env.mongo.collection('categories') #Connection Pool from Goliath ENV 
     coll.find({}) 
    end 
    end 
end 

class App < Goliath::API 
    def response(env) 
    API.call(env) 
    end 
end 

preatty простой в конце. Если вы хотите глубже взглянуть на https://github.com/lgs/GGM.

0

Я думаю, вы должны предоставить метод в тесте, чтобы определить класс вашего приложения

def app 
    App 
end 

Обновление

Попробуйте API-класс вместо

def app 
    API 
end 
+0

не работает, см UPDATE на главном Q. –

+0

я ничего не знаю Голиафа. Но кажется, что это должно сработать, если вы используете API-класс вместо App –

+0

сейчас я получаю неопределенный метод 'mongo ', см. Последний UPDATE –

0

добавить другой пример POST:

require 'spec_helper' 

describe V1::API do 
    it "login" do 
    with_api V1::Login do 


     post_request(path: "/v1/login", :head => {'authorization' => HTTP_BASIC_HEADER }, :body =>{mobile: 18600112233}) do |async| 

     async.response_header.status.should == 201 
     async.response.should == { mobile: '18600112233' }.to_json 
     end 
    end 
    end 

end 
Смежные вопросы