add ruby spec for configuration, api client, replace should with expect

This commit is contained in:
wing328 2016-05-10 14:18:06 +08:00
parent 65ee4cb835
commit d54877b5d3
15 changed files with 660 additions and 85 deletions

View File

@ -286,8 +286,9 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
for (String templateName : config.modelTestTemplateFiles().keySet()) { for (String templateName : config.modelTestTemplateFiles().keySet()) {
String suffix = config.modelTestTemplateFiles().get(templateName); String suffix = config.modelTestTemplateFiles().get(templateName);
String filename = config.modelTestFileFolder() + File.separator + config.toModelTestFilename(name) + suffix; String filename = config.modelTestFileFolder() + File.separator + config.toModelTestFilename(name) + suffix;
if (!config.shouldOverwrite(filename)) { // do not overwrite test file that already exists
LOGGER.info("Skipped overwriting " + filename); if (new File(filename).exists()) {
LOGGER.info("File exists. Skipped overwriting " + filename);
continue; continue;
} }
String templateFile = getFullTemplateFile(config, templateName); String templateFile = getFullTemplateFile(config, templateName);
@ -419,11 +420,11 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
// to generate api test files // to generate api test files
for (String templateName : config.apiTestTemplateFiles().keySet()) { for (String templateName : config.apiTestTemplateFiles().keySet()) {
String filename = config.apiTestFilename(templateName, tag); String filename = config.apiTestFilename(templateName, tag);
if (!config.shouldOverwrite(filename) && new File(filename).exists()) { // do not overwrite test file that already exists
LOGGER.info("Skipped overwriting " + filename); if (new File(filename).exists()) {
LOGGER.info("File exists. Skipped overwriting " + filename);
continue; continue;
} }
String templateFile = getFullTemplateFile(config, templateName); String templateFile = getFullTemplateFile(config, templateName);
String template = readTemplate(templateFile); String template = readTemplate(templateFile);
Template tmpl = Mustache.compiler() Template tmpl = Mustache.compiler()

View File

@ -224,6 +224,10 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
writeOptional(outputFolder, new SupportingFile("rspec.mustache", "", ".rspec"));
writeOptional(outputFolder, new SupportingFile("spec_helper.mustache", specFolder, "spec_helper.rb"));
writeOptional(outputFolder, new SupportingFile("configuration_spec.mustache", specFolder, "configuration_spec.rb"));
writeOptional(outputFolder, new SupportingFile("api_client_spec.mustache", specFolder, "api_client_spec.rb"));
} }
@Override @Override
@ -644,10 +648,11 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
this.gemAuthorEmail = gemAuthorEmail; this.gemAuthorEmail = gemAuthorEmail;
} }
@Override @Override
public boolean shouldOverwrite(String filename) { public boolean shouldOverwrite(String filename) {
// skip spec file as the file might have been updated with new test cases // skip spec file as the file might have been updated with new test cases
return super.shouldOverwrite(filename) && !filename.endsWith("_spec.rb"); return !(skipOverwrite && new File(filename).exists());
//
//return super.shouldOverwrite(filename) && !filename.endsWith("_spec.rb");
} }
} }

View File

@ -0,0 +1,273 @@
require 'spec_helper'
describe {{moduleName}}::ApiClient do
context 'initialization' do
context 'URL stuff' do
context 'host' do
it 'removes http from host' do
{{moduleName}}.configure { |c| c.host = 'http://example.com' }
expect({{moduleName}}::Configuration.default.host).to eq('example.com')
end
it 'removes https from host' do
{{moduleName}}.configure { |c| c.host = 'https://wookiee.com' }
expect({{moduleName}}::ApiClient.default.config.host).to eq('wookiee.com')
end
it 'removes trailing path from host' do
{{moduleName}}.configure { |c| c.host = 'hobo.com/v4' }
expect({{moduleName}}::Configuration.default.host).to eq('hobo.com')
end
end
context 'base_path' do
it "prepends a slash to base_path" do
{{moduleName}}.configure { |c| c.base_path = 'v4/dog' }
expect({{moduleName}}::Configuration.default.base_path).to eq('/v4/dog')
end
it "doesn't prepend a slash if one is already there" do
{{moduleName}}.configure { |c| c.base_path = '/v4/dog' }
expect({{moduleName}}::Configuration.default.base_path).to eq('/v4/dog')
end
it "ends up as a blank string if nil" do
{{moduleName}}.configure { |c| c.base_path = nil }
expect({{moduleName}}::Configuration.default.base_path).to eq('')
end
end
end
end
describe "#update_params_for_auth!" do
it "sets header api-key parameter with prefix" do
{{moduleName}}.configure do |c|
c.api_key_prefix['api_key'] = 'PREFIX'
c.api_key['api_key'] = 'special-key'
end
api_client = {{moduleName}}::ApiClient.new
config2 = {{moduleName}}::Configuration.new do |c|
c.api_key_prefix['api_key'] = 'PREFIX2'
c.api_key['api_key'] = 'special-key2'
end
api_client2 = {{moduleName}}::ApiClient.new(config2)
auth_names = ['api_key', 'unknown']
header_params = {}
query_params = {}
api_client.update_params_for_auth! header_params, query_params, auth_names
expect(header_params).to eq({'api_key' => 'PREFIX special-key'})
expect(query_params).to eq({})
header_params = {}
query_params = {}
api_client2.update_params_for_auth! header_params, query_params, auth_names
expect(header_params).to eq({'api_key' => 'PREFIX2 special-key2'})
expect(query_params).to eq({})
end
it "sets header api-key parameter without prefix" do
{{moduleName}}.configure do |c|
c.api_key_prefix['api_key'] = nil
c.api_key['api_key'] = 'special-key'
end
api_client = {{moduleName}}::ApiClient.new
header_params = {}
query_params = {}
auth_names = ['api_key', 'unknown']
api_client.update_params_for_auth! header_params, query_params, auth_names
expect(header_params).to eq({'api_key' => 'special-key'})
expect(query_params).to eq({})
end
end
describe "timeout in #build_request" do
let(:config) { {{moduleName}}::Configuration.new }
let(:api_client) { {{moduleName}}::ApiClient.new(config) }
it "defaults to 0" do
expect({{moduleName}}::Configuration.default.timeout).to eq(0)
expect(config.timeout).to eq(0)
request = api_client.build_request(:get, '/test')
expect(request.options[:timeout]).to eq(0)
end
it "can be customized" do
config.timeout = 100
request = api_client.build_request(:get, '/test')
expect(request.options[:timeout]).to eq(100)
end
end
describe "#deserialize" do
it "handles Array<Integer>" do
api_client = {{moduleName}}::ApiClient.new
headers = {'Content-Type' => 'application/json'}
response = double('response', headers: headers, body: '[12, 34]')
data = api_client.deserialize(response, 'Array<Integer>')
expect(data).to be_instance_of(Array)
expect(data).to eq([12, 34])
end
it "handles Array<Array<Integer>>" do
api_client = {{moduleName}}::ApiClient.new
headers = {'Content-Type' => 'application/json'}
response = double('response', headers: headers, body: '[[12, 34], [56]]')
data = api_client.deserialize(response, 'Array<Array<Integer>>')
expect(data).to be_instance_of(Array)
expect(data).to eq([[12, 34], [56]])
end
it "handles Hash<String, String>" do
api_client = {{moduleName}}::ApiClient.new
headers = {'Content-Type' => 'application/json'}
response = double('response', headers: headers, body: '{"message": "Hello"}')
data = api_client.deserialize(response, 'Hash<String, String>')
expect(data).to be_instance_of(Hash)
expect(data).to eq({:message => 'Hello'})
end
it "handles Hash<String, Pet>" do
api_client = {{moduleName}}::ApiClient.new
headers = {'Content-Type' => 'application/json'}
response = double('response', headers: headers, body: '{"pet": {"id": 1}}')
data = api_client.deserialize(response, 'Hash<String, Pet>')
expect(data).to be_instance_of(Hash)
expect(data.keys).to eq([:pet])
pet = data[:pet]
expect(pet).to be_instance_of({{moduleName}}::Pet)
expect(pet.id).to eq(1)
end
it "handles Hash<String, Hash<String, Pet>>" do
api_client = {{moduleName}}::ApiClient.new
headers = {'Content-Type' => 'application/json'}
response = double('response', headers: headers, body: '{"data": {"pet": {"id": 1}}}')
result = api_client.deserialize(response, 'Hash<String, Hash<String, Pet>>')
expect(result).to be_instance_of(Hash)
expect(result.keys).to match_array([:data])
data = result[:data]
expect(data).to be_instance_of(Hash)
expect(data.keys).to match_array([:pet])
pet = data[:pet]
expect(pet).to be_instance_of({{moduleName}}::Pet)
expect(pet.id).to eq(1)
end
end
describe "#object_to_hash" do
it "ignores nils and includes empty arrays" do
api_client = {{moduleName}}::ApiClient.new
pet = {{moduleName}}::Pet.new
pet.id = 1
pet.name = ''
pet.status = nil
pet.photo_urls = nil
pet.tags = []
expected = {id: 1, name: '', tags: []}
expect(api_client.object_to_hash(pet)).to eq(expected)
end
end
describe "#build_collection_param" do
let(:param) { ['aa', 'bb', 'cc'] }
let(:api_client) { {{moduleName}}::ApiClient.new }
it "works for csv" do
expect(api_client.build_collection_param(param, :csv)).to eq('aa,bb,cc')
end
it "works for ssv" do
expect(api_client.build_collection_param(param, :ssv)).to eq('aa bb cc')
end
it "works for tsv" do
expect(api_client.build_collection_param(param, :tsv)).to eq("aa\tbb\tcc")
end
it "works for pipes" do
expect(api_client.build_collection_param(param, :pipes)).to eq('aa|bb|cc')
end
it "works for multi" do
expect(api_client.build_collection_param(param, :multi)).to eq(['aa', 'bb', 'cc'])
end
it "fails for invalid collection format" do
expect(proc { api_client.build_collection_param(param, :INVALID) }).to raise_error(RuntimeError, 'unknown collection format: :INVALID')
end
end
describe "#json_mime?" do
let(:api_client) { {{moduleName}}::ApiClient.new }
it "works" do
expect(api_client.json_mime?(nil)).to eq false
expect(api_client.json_mime?('')).to eq false
expect(api_client.json_mime?('application/json')).to eq true
expect(api_client.json_mime?('application/json; charset=UTF8')).to eq true
expect(api_client.json_mime?('APPLICATION/JSON')).to eq true
expect(api_client.json_mime?('application/xml')).to eq false
expect(api_client.json_mime?('text/plain')).to eq false
expect(api_client.json_mime?('application/jsonp')).to eq false
end
end
describe "#select_header_accept" do
let(:api_client) { {{moduleName}}::ApiClient.new }
it "works" do
expect(api_client.select_header_accept(nil)).to be_nil
expect(api_client.select_header_accept([])).to be_nil
expect(api_client.select_header_accept(['application/json'])).to eq('application/json')
expect(api_client.select_header_accept(['application/xml', 'application/json; charset=UTF8'])).to eq('application/json; charset=UTF8')
expect(api_client.select_header_accept(['APPLICATION/JSON', 'text/html'])).to eq('APPLICATION/JSON')
expect(api_client.select_header_accept(['application/xml'])).to eq('application/xml')
expect(api_client.select_header_accept(['text/html', 'application/xml'])).to eq('text/html,application/xml')
end
end
describe "#select_header_content_type" do
let(:api_client) { {{moduleName}}::ApiClient.new }
it "works" do
expect(api_client.select_header_content_type(nil)).to eq('application/json')
expect(api_client.select_header_content_type([])).to eq('application/json')
expect(api_client.select_header_content_type(['application/json'])).to eq('application/json')
expect(api_client.select_header_content_type(['application/xml', 'application/json; charset=UTF8'])).to eq('application/json; charset=UTF8')
expect(api_client.select_header_content_type(['APPLICATION/JSON', 'text/html'])).to eq('APPLICATION/JSON')
expect(api_client.select_header_content_type(['application/xml'])).to eq('application/xml')
expect(api_client.select_header_content_type(['text/plain', 'application/xml'])).to eq('text/plain')
end
end
describe "#sanitize_filename" do
let(:api_client) { {{moduleName}}::ApiClient.new }
it "works" do
expect(api_client.sanitize_filename('sun')).to eq('sun')
expect(api_client.sanitize_filename('sun.gif')).to eq('sun.gif')
expect(api_client.sanitize_filename('../sun.gif')).to eq('sun.gif')
expect(api_client.sanitize_filename('/var/tmp/sun.gif')).to eq('sun.gif')
expect(api_client.sanitize_filename('./sun.gif')).to eq('sun.gif')
expect(api_client.sanitize_filename('..\sun.gif')).to eq('sun.gif')
expect(api_client.sanitize_filename('\var\tmp\sun.gif')).to eq('sun.gif')
expect(api_client.sanitize_filename('c:\var\tmp\sun.gif')).to eq('sun.gif')
expect(api_client.sanitize_filename('.\sun.gif')).to eq('sun.gif')
end
end
end

View File

@ -20,7 +20,7 @@ require 'json'
describe 'test an instance of {{classname}}' do describe 'test an instance of {{classname}}' do
it 'should create an instact of {{classname}}' do it 'should create an instact of {{classname}}' do
@instance.should be_a({{moduleName}}::{{classname}}) expect(@instance).to be_instance_of({{moduleName}}::{{classname}})
end end
end end
@ -34,11 +34,7 @@ require 'json'
{{/required}}{{/allParams}} # @return [{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}] {{/required}}{{/allParams}} # @return [{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}]
describe '{{operationId}} test' do describe '{{operationId}} test' do
it "should work" do it "should work" do
# assertion here # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
# should be_a()
# should be_nil
# should ==
# should_not ==
end end
end end

View File

@ -0,0 +1,25 @@
require 'spec_helper'
describe {{moduleName}}::Configuration do
let(:config) { {{moduleName}}::Configuration.default }
before(:each) do
{{moduleName}}.configure do |c|
c.host = 'petstore.swagger.io'
c.base_path = 'v2'
end
end
describe '#base_url' do
it 'should have the default value' do
expect(config.base_url).to eq('http://petstore.swagger.io/v2')
end
it 'should remove trailing slashes' do
[nil, '', '/', '//'].each do |base_path|
config.base_path = base_path
expect(config.base_url).to eq('http://petstore.swagger.io')
end
end
end
end

View File

@ -21,17 +21,13 @@ require 'date'
describe 'test an instance of {{classname}}' do describe 'test an instance of {{classname}}' do
it 'should create an instact of {{classname}}' do it 'should create an instact of {{classname}}' do
@instance.should be_a({{moduleName}}::{{classname}}) expect(@instance).to be_instance_of({{moduleName}}::{{classname}})
end end
end end
{{#vars}} {{#vars}}
describe 'test attribute "{{{name}}}"' do describe 'test attribute "{{{name}}}"' do
it 'should work' do it 'should work' do
# assertion here # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
# should be_a()
# should be_nil
# should ==
# should_not ==
end end
end end

View File

@ -0,0 +1,2 @@
--color
--require spec_helper

View File

@ -0,0 +1,99 @@
# load the gem
require '{{{gemName}}}'
# The following was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# The `.rspec` file also contains a few flags that are not defaults but that
# users commonly want.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
# These two settings work together to allow you to limit a spec run
# to individual examples or groups you care about by tagging them with
# `:focus` metadata. When nothing is tagged with `:focus`, all examples
# get run.
config.filter_run :focus
config.run_all_when_everything_filtered = true
# Allows RSpec to persist some state between runs in order to support
# the `--only-failures` and `--next-failure` CLI options. We recommend
# you configure your source control system to ignore this file.
config.example_status_persistence_file_path = "spec/examples.txt"
# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
# - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
config.disable_monkey_patching!
# This setting enables warnings. It's recommended, but in some cases may
# be too noisy due to issues in dependencies.
config.warnings = true
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = 'doc'
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
=end
end

View File

@ -0,0 +1,2 @@
--color
--require spec_helper

View File

@ -8,7 +8,7 @@ This SDK is automatically generated by the [Swagger Codegen](https://github.com/
- API version: 1.0.0 - API version: 1.0.0
- Package version: 1.0.0 - Package version: 1.0.0
- Build date: 2016-05-06T16:33:11.754+08:00 - Build date: 2016-05-10T14:06:27.504+08:00
- Build package: class io.swagger.codegen.languages.RubyClientCodegen - Build package: class io.swagger.codegen.languages.RubyClientCodegen
## Installation ## Installation

View File

@ -0,0 +1,40 @@
=begin
Swagger Petstore
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose.
OpenAPI spec version: 1.0.0
Contact: apiteam@swagger.io
Generated by: https://github.com/swagger-api/swagger-codegen.git
License: Apache 2.0
http://www.apache.org/licenses/LICENSE-2.0.html
Terms of Service: http://swagger.io/terms/
=end
require 'spec_helper'
require 'json'
require 'date'
# Unit tests for Petstore::AnimalFarm
# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen)
# Please update as you see appropriate
describe 'AnimalFarm' do
before do
# run before each test
@instance = Petstore::AnimalFarm.new
end
after do
# run after each test
end
describe 'test an instance of AnimalFarm' do
it 'should create an instact of AnimalFarm' do
expect(@instance).to be_instance_of(Petstore::AnimalFarm)
end
end
end

View File

@ -0,0 +1,40 @@
=begin
Swagger Petstore
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose.
OpenAPI spec version: 1.0.0
Contact: apiteam@swagger.io
Generated by: https://github.com/swagger-api/swagger-codegen.git
License: Apache 2.0
http://www.apache.org/licenses/LICENSE-2.0.html
Terms of Service: http://swagger.io/terms/
=end
require 'spec_helper'
require 'json'
require 'date'
# Unit tests for Petstore::EnumClass
# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen)
# Please update as you see appropriate
describe 'EnumClass' do
before do
# run before each test
@instance = Petstore::EnumClass.new
end
after do
# run after each test
end
describe 'test an instance of EnumClass' do
it 'should create an instact of EnumClass' do
expect(@instance).to be_instance_of(Petstore::EnumClass)
end
end
end

View File

@ -0,0 +1,58 @@
=begin
Swagger Petstore
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose.
OpenAPI spec version: 1.0.0
Contact: apiteam@swagger.io
Generated by: https://github.com/swagger-api/swagger-codegen.git
License: Apache 2.0
http://www.apache.org/licenses/LICENSE-2.0.html
Terms of Service: http://swagger.io/terms/
=end
require 'spec_helper'
require 'json'
require 'date'
# Unit tests for Petstore::EnumTest
# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen)
# Please update as you see appropriate
describe 'EnumTest' do
before do
# run before each test
@instance = Petstore::EnumTest.new
end
after do
# run after each test
end
describe 'test an instance of EnumTest' do
it 'should create an instact of EnumTest' do
expect(@instance).to be_instance_of(Petstore::EnumTest)
end
end
describe 'test attribute "enum_string"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "enum_integer"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "enum_number"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
end

View File

@ -25,10 +25,20 @@ describe 'Pet' do
before do before do
# run before each test # run before each test
@instance = Petstore::Pet.new @instance = Petstore::Pet.new
@pet_api = Petstore::PetApi.new(API_CLIENT)
@pet_id = prepare_pet(@pet_api)
end end
after do after do
# run after each test # run after each test
# remove the testing pet
begin
@pet_api.delete_pet(@pet_id)
rescue Petstore::ApiError => e
# ignore ApiError 404 (Not Found)
raise e if e.code != 404
end
end end
describe 'test an instance of Pet' do describe 'test an instance of Pet' do

View File

@ -1,71 +1,99 @@
require 'rubygems' # This file was generated by the `rspec --init` command. Conventionally, all
require 'bundler/setup' # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
require 'petstore' # The generated `.rspec` file contains `--require spec_helper` which will cause
require 'vcr' # this file to always be loaded, without a need to explicitly require it in any
require 'typhoeus' # files.
require 'json' #
require 'yaml' # Given that it is always loaded, you are encouraged to keep this file as
require 'rspec' # light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# The `.rspec` file also contains a few flags that are not defaults but that
# users commonly want.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config| RSpec.configure do |config|
# some (optional) config here # rspec-expectations config goes here. You can use an alternate
config.expect_with :rspec do |c| # assertion/expectation library such as wrong or the stdlib/minitest
c.syntax = :should # assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end end
config.mock_with :rspec do |c|
c.syntax = :should # rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end end
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
# These two settings work together to allow you to limit a spec run
# to individual examples or groups you care about by tagging them with
# `:focus` metadata. When nothing is tagged with `:focus`, all examples
# get run.
config.filter_run :focus
config.run_all_when_everything_filtered = true
# Allows RSpec to persist some state between runs in order to support
# the `--only-failures` and `--next-failure` CLI options. We recommend
# you configure your source control system to ignore this file.
config.example_status_persistence_file_path = "spec/examples.txt"
# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
# - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
config.disable_monkey_patching!
# This setting enables warnings. It's recommended, but in some cases may
# be too noisy due to issues in dependencies.
config.warnings = true
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = 'doc'
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
=end
end end
require 'SwaggerClient'
WebMock.allow_net_connect! if defined? WebMock
def help
puts "\nOh noes! You gotta stuff your swagger credentials in ~/.swagger.yml like so:\n\n"
puts "api_key: '12345abcdefg'"
puts "username: 'fumanchu'"
puts "password: 'kalamazoo'\n\n"
exit
end
# no longer reading credentials (not used) from file (20150413)
# Parse ~/.swagger.yml for user credentials
#begin
# CREDENTIALS = YAML::load_file(File.join(ENV['HOME'], ".swagger.yml")).symbolize_keys
#rescue
# help
#end
API_CLIENT = Petstore::ApiClient.new(Petstore::Configuration.new)
def random_id
rand(1000000) + 20000
end
# create a random pet, return its id
def prepare_pet(pet_api)
pet_id = random_id
category = Petstore::Category.new('id' => 20002, 'name' => 'category test')
tag = Petstore::Tag.new('id' => 30002, 'name' => 'tag test')
pet = Petstore::Pet.new('id' => pet_id, 'name' => "RUBY UNIT TESTING", 'photo_urls' => 'photo url',
'category' => category, 'tags' => [tag], 'status' => 'pending')
pet_api.add_pet(pet)
return pet_id
end
# create a random order, return its id
def prepare_store(store_api)
order_id = 5
order = Petstore::Order.new("id" => order_id,
"petId" => 123,
"quantity" => 789,
"shipDate" => "2015-04-06T23:42:01.678Z",
"status" => "placed",
"complete" => false)
store_api.place_order(order)
return order_id
end
# A random string to tack onto stuff to ensure we're not seeing
# data from a previous test run
RAND = ("a".."z").to_a.sample(8).join