diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 00000000..1f89646d --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,26 @@ +# .git-blame-ignore-revs + +# What is this file? + +# To limit the impact of 'unimportant' bulk commits, like big a PR full of rubocop fixes, git 2.23 adds a new option to git blame. +# Using --ignore-rev, or this file, one can specify a commit to be ignored by git blame. +# Lines changed by the ignored commit will be attributed to the previous commit touching that line instead. +# This means that even after our bulk style change, we can get back a meaningful context for the 'real' changes to our code. + +# How do I use it? + +# The file should contain the full (40 character) commit hashes. +# Lines starting with a # are considered comments and can be used to explain what makes the given commit(s) unimportant. +# Commit order in the file is not important. + +# Lint: Fix Style/StringLiterals etc. offenses +afbf222941a6afbc9ac0a4db49534fa15436ae69 + +# Lint: Fix layout offenses +3db45d38aa28dbbd7830658254ec9c59c02a29e0 + +# Lint: Fix simple offenses +0221a908fec6d2a55ce645c5a17a074c93957be3 + +# Move require of spec_helper into .rspec +8f09a851fb6feae50769ffb5430b3f0ebe3053b4 diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index aea07608..451d0cc3 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -9,8 +9,8 @@ on: - spec_live jobs: - test-and-lint: - name: Test and lint + test: + name: Test runs-on: ubuntu-latest strategy: fail-fast: false @@ -30,10 +30,9 @@ jobs: with: bundler-cache: true ruby-version: ${{ matrix.ruby }} - - name: Test and Lint - run: | - bundle exec rake - bundle exec rubocop + - name: Test + run: bundle exec rake + spec-live: name: Spec live if: github.repository == 'zendesk/zendesk_api_client_rb' @@ -54,3 +53,16 @@ jobs: bundle exec rake clean_live set_ci_credentials spec:live || bundle exec rake clean_live && bundle exec rspec spec/live --only-failures + + lint: + name: Lint + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v5 + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + bundler-cache: true + - name: Lint + run: bundle exec rake standard diff --git a/.rspec b/.rspec index 09127182..e2b6e7ed 100644 --- a/.rspec +++ b/.rspec @@ -1,2 +1,3 @@ --color --order random +--require core/spec_helper diff --git a/.rubocop.yml b/.rubocop.yml deleted file mode 100644 index 286003c4..00000000 --- a/.rubocop.yml +++ /dev/null @@ -1,58 +0,0 @@ -inherit_from: .rubocop_todo.yml - -AllCops: - TargetRubyVersion: 3.1 - DisplayCopNames: true - SuggestExtensions: false - NewCops: enable - Exclude: - - .git/**/* - - spec/core/middleware/response/sanitize_response_spec.rb - - vendor/**/* - -# Align ends correctly. -Layout/EndAlignment: - EnforcedStyleAlignWith: variable - -# Align the elements of a hash literal if they span more than one line. -Layout/HashAlignment: - EnforcedLastArgumentHashStyle: ignore_implicit - -# Align the parameters of a method call if they span more than one line. -Layout/ParameterAlignment: - EnforcedStyle: with_fixed_indentation - -# Checks the indentation of hanging closing parentheses. -Layout/ClosingParenthesisIndentation: - Enabled: false - -# Checks the indentation of the first parameter in a method call. -Layout/FirstParameterIndentation: - EnforcedStyle: consistent - -# Checks indentation of method calls with the dot operator that span more than one line. -Layout/MultilineMethodCallIndentation: - EnforcedStyle: indented - -# Checks indentation of binary operations that span more than one line. -Layout/MultilineOperationIndentation: - EnforcedStyle: indented - -Metrics: - Enabled: false - -Style/DoubleNegation: - Enabled: false - -Style/OptionalBooleanParameter: - Enabled: false - -Naming/PredicateMethod: - Enabled: false - -Style/HashEachMethods: - Enabled: false - -Style/RedundantFetchBlock: - Exclude: - - spec/core/lru_cache_spec.rb diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml deleted file mode 100644 index eb88916d..00000000 --- a/.rubocop_todo.yml +++ /dev/null @@ -1,523 +0,0 @@ -# This configuration was generated by -# `rubocop --auto-gen-config` -# on 2025-08-12 17:05:00 UTC using RuboCop version 1.79.2. -# The point is for the user to remove these configuration records -# one by one as the offenses are removed from the code base. -# Note that changes in the inspected code, or installation of new -# versions of RuboCop, may require this file to be generated again. - -# Offense count: 5 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: TreatCommentsAsGroupSeparators, ConsiderPunctuation, Include. -# Include: **/*.gemfile, **/Gemfile, **/gems.rb -Bundler/OrderedGems: - Exclude: - - 'Gemfile' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: TreatCommentsAsGroupSeparators, ConsiderPunctuation, Include. -# Include: **/*.gemspec -Gemspec/OrderedDependencies: - Exclude: - - 'zendesk_api.gemspec' - -# Offense count: 19 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: leading, trailing -Layout/DotPosition: - Exclude: - - 'lib/zendesk_api/helpers.rb' - - 'spec/core/collection_spec.rb' - - 'spec/core/data_namespace_spec.rb' - - 'spec/core/middleware/request/retry_spec.rb' - -# Offense count: 14 -# This cop supports safe autocorrection (--autocorrect). -Layout/EmptyLineAfterGuardClause: - Exclude: - - 'lib/zendesk_api/actions.rb' - - 'lib/zendesk_api/client.rb' - - 'lib/zendesk_api/collection.rb' - - 'lib/zendesk_api/resource.rb' - - 'lib/zendesk_api/resources.rb' - - 'lib/zendesk_api/sideloading.rb' - - 'spec/live/ticket_spec.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: AllowMultipleStyles, EnforcedHashRocketStyle, EnforcedColonStyle, EnforcedLastArgumentHashStyle. -# SupportedHashRocketStyles: key, separator, table -# SupportedColonStyles: key, separator, table -# SupportedLastArgumentHashStyles: always_inspect, always_ignore, ignore_implicit, ignore_explicit -Layout/HashAlignment: - Exclude: - - 'spec/live/user_view_spec.rb' - -# Offense count: 8 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: symmetrical, new_line, same_line -Layout/MultilineMethodCallBraceLayout: - Exclude: - - 'spec/core/bulk_actions_spec.rb' - - 'spec/core/collection_spec.rb' - -# Offense count: 3 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces. -# SupportedStyles: space, no_space -# SupportedStylesForEmptyBraces: space, no_space -Layout/SpaceBeforeBlockBraces: - Exclude: - - 'spec/core/middleware/response/parse_iso_dates_spec.rb' - - 'spec/core/read_resource_spec.rb' - - 'spec/core/resource_spec.rb' - -# Offense count: 2 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces, SpaceBeforeBlockParameters. -# SupportedStyles: space, no_space -# SupportedStylesForEmptyBraces: space, no_space -Layout/SpaceInsideBlockBraces: - Exclude: - - 'lib/zendesk_api/association.rb' - -# Offense count: 9 -# This cop supports unsafe autocorrection (--autocorrect-all). -# Configuration parameters: AllowSafeAssignment. -Lint/AssignmentInCondition: - Exclude: - - 'lib/zendesk_api/actions.rb' - - 'lib/zendesk_api/association.rb' - - 'lib/zendesk_api/associations.rb' - - 'lib/zendesk_api/client.rb' - - 'lib/zendesk_api/resources.rb' - -# Offense count: 1 -# This cop supports unsafe autocorrection (--autocorrect-all). -Lint/BooleanSymbol: - Exclude: - - 'spec/live/target_spec.rb' - -# Offense count: 2 -# Configuration parameters: AllowedMethods. -# AllowedMethods: enums -Lint/ConstantDefinitionInBlock: - Exclude: - - 'spec/core/collection_spec.rb' - - 'spec/core/resource_spec.rb' - -# Offense count: 2 -Lint/DuplicateMethods: - Exclude: - - 'lib/zendesk_api/resource.rb' - -# Offense count: 1 -# Configuration parameters: AllowComments, AllowEmptyLambdas. -Lint/EmptyBlock: - Exclude: - - 'spec/core/collection_spec.rb' - -# Offense count: 2 -# Configuration parameters: AllowComments. -Lint/EmptyClass: - Exclude: - - 'spec/core/data_namespace_spec.rb' - - 'spec/fixtures/test_resources.rb' - -# Offense count: 1 -# This cop supports unsafe autocorrection (--autocorrect-all). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: standard_error, runtime_error -Lint/InheritException: - Exclude: - - 'spec/core/collection_spec.rb' - -# Offense count: 2 -# Configuration parameters: AllowedParentClasses. -Lint/MissingSuper: - Exclude: - - 'lib/zendesk_api/middleware/request/etag_cache.rb' - - 'lib/zendesk_api/resource.rb' - -# Offense count: 10 -# This cop supports safe autocorrection (--autocorrect). -Lint/RedundantStringCoercion: - Exclude: - - 'lib/zendesk_api/middleware/response/logger.rb' - - 'spec/live/macro_spec.rb' - - 'spec/macros/resource_macros.rb' - -# Offense count: 1 -# Configuration parameters: IgnoreImplicitReferences. -Lint/ShadowedArgument: - Exclude: - - 'lib/zendesk_api/association.rb' - -# Offense count: 1 -# Configuration parameters: AllowComments, AllowNil. -Lint/SuppressedException: - Exclude: - - 'spec/core/collection_spec.rb' - -# Offense count: 4 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: AutoCorrect, IgnoreEmptyBlocks, AllowUnusedKeywordArguments. -Lint/UnusedBlockArgument: - Exclude: - - 'lib/zendesk_api/track_changes.rb' - - 'spec/core/collection_spec.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: AutoCorrect, AllowUnusedKeywordArguments, IgnoreEmptyMethods, IgnoreNotImplementedMethods, NotImplementedExceptions. -# NotImplementedExceptions: NotImplementedError -Lint/UnusedMethodArgument: - Exclude: - - 'spec/fixtures/test_resources.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: AutoCorrect, CheckForMethodsWithNoSideEffects. -Lint/Void: - Exclude: - - 'lib/zendesk_api/middleware/request/encode_json.rb' - -# Offense count: 3 -Naming/AccessorMethodName: - Exclude: - - 'lib/zendesk_api/lru_cache.rb' - - 'lib/zendesk_api/pagination.rb' - -# Offense count: 1 -# This cop supports unsafe autocorrection (--autocorrect-all). -# Configuration parameters: EnforcedStyleForLeadingUnderscores. -# SupportedStylesForLeadingUnderscores: disallowed, required, optional -Naming/MemoizedInstanceVariableName: - Exclude: - - 'lib/zendesk_api/collection.rb' - -# Offense count: 1 -# Configuration parameters: NamePrefix, ForbiddenPrefixes, AllowedMethods, MethodDefinitionMacros, UseSorbetSigs. -# NamePrefix: is_, has_, have_, does_ -# ForbiddenPrefixes: is_, has_, have_, does_ -# AllowedMethods: is_a? -# MethodDefinitionMacros: define_method, define_singleton_method -Naming/PredicatePrefix: - Exclude: - - 'spec/**/*' - - 'lib/zendesk_api/associations.rb' - -# Offense count: 11 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: prefer_alias, prefer_alias_method -Style/Alias: - Exclude: - - 'lib/zendesk_api/resource.rb' - - 'lib/zendesk_api/resources.rb' - - 'lib/zendesk_api/track_changes.rb' - -# Offense count: 1 -# This cop supports unsafe autocorrection (--autocorrect-all). -Style/ArrayIntersect: - Exclude: - - 'lib/zendesk_api/search.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -Style/BlockComments: - Exclude: - - 'spec/core/trackie_spec.rb' - -# Offense count: 10 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle, ProceduralMethods, FunctionalMethods, AllowedMethods, AllowedPatterns, AllowBracesOnProceduralOneLiners, BracesRequiredMethods. -# SupportedStyles: line_count_based, semantic, braces_for_chaining, always_braces -# ProceduralMethods: benchmark, bm, bmbm, create, each_with_object, measure, new, realtime, tap, with_object -# FunctionalMethods: let, let!, subject, watch -# AllowedMethods: lambda, proc, it -Style/BlockDelimiters: - Exclude: - - 'lib/zendesk_api/association.rb' - - 'spec/core/middleware/request/encode_json_spec.rb' - - 'spec/core/middleware/request/retry_spec.rb' - - 'spec/core/middleware/response/parse_iso_dates_spec.rb' - - 'spec/core/read_resource_spec.rb' - - 'spec/core/resource_spec.rb' - -# Offense count: 9 -# This cop supports unsafe autocorrection (--autocorrect-all). -# Configuration parameters: EnforcedStyle, EnforcedStyleForClasses, EnforcedStyleForModules. -# SupportedStyles: nested, compact -# SupportedStylesForClasses: ~, nested, compact -# SupportedStylesForModules: ~, nested, compact -Style/ClassAndModuleChildren: - Exclude: - - 'lib/zendesk_api/lru_cache.rb' - - 'spec/core/data_namespace_spec.rb' - - 'spec/core/resource_spec.rb' - - 'spec/fixtures/test_resources.rb' - -# Offense count: 99 -# Configuration parameters: AllowedConstants. -Style/Documentation: - Exclude: - - 'spec/**/*' - - 'test/**/*' - - 'lib/zendesk_api.rb' - - 'lib/zendesk_api/actions.rb' - - 'lib/zendesk_api/associations.rb' - - 'lib/zendesk_api/error.rb' - - 'lib/zendesk_api/middleware/request/encode_json.rb' - - 'lib/zendesk_api/middleware/request/url_based_access_token.rb' - - 'lib/zendesk_api/middleware/response/parse_json.rb' - - 'lib/zendesk_api/middleware/response/raise_error.rb' - - 'lib/zendesk_api/middleware/response/sanitize_response.rb' - - 'lib/zendesk_api/resource.rb' - - 'lib/zendesk_api/resources.rb' - - 'util/resource_handler.rb' - - 'util/verb_handler.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -Style/EachWithObject: - Exclude: - - 'lib/zendesk_api/associations.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -Style/ExpandPathArguments: - Exclude: - - 'zendesk_api.gemspec' - -# Offense count: 126 -# This cop supports unsafe autocorrection (--autocorrect-all). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: always, always_true, never -Style/FrozenStringLiteralComment: - Enabled: false - -# Offense count: 3 -# Configuration parameters: AllowedVariables. -Style/GlobalVars: - Exclude: - - 'spec/core/spec_helper.rb' - -# Offense count: 11 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: MinBodyLength, AllowConsecutiveConditionals. -Style/GuardClause: - Exclude: - - 'lib/zendesk_api/actions.rb' - - 'lib/zendesk_api/association.rb' - - 'lib/zendesk_api/client.rb' - - 'lib/zendesk_api/collection.rb' - - 'lib/zendesk_api/middleware/request/upload.rb' - - 'lib/zendesk_api/middleware/response/parse_json.rb' - - 'lib/zendesk_api/resources.rb' - -# Offense count: 865 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle, EnforcedShorthandSyntax, UseHashRocketsWithSymbolValues, PreferHashRocketsForNonAlnumEndingSymbols. -# SupportedStyles: ruby19, hash_rockets, no_mixed_keys, ruby19_no_mixed_keys -# SupportedShorthandSyntax: always, never, either, consistent, either_consistent -Style/HashSyntax: - Enabled: false - -# Offense count: 27 -# This cop supports safe autocorrection (--autocorrect). -Style/IfUnlessModifier: - Enabled: false - -# Offense count: 2 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: line_count_dependent, lambda, literal -Style/Lambda: - Exclude: - - 'spec/core/middleware/request/encode_json_spec.rb' - - 'spec/core/middleware/request/upload_spec.rb' - -# Offense count: 1 -Style/MissingRespondToMissing: - Exclude: - - 'lib/zendesk_api/client.rb' - -# Offense count: 1 -Style/MixinUsage: - Exclude: - - 'spec/core/spec_helper.rb' - -# Offense count: 4 -# This cop supports safe autocorrection (--autocorrect). -Style/MultilineIfModifier: - Exclude: - - 'spec/macros/resource_macros.rb' - -# Offense count: 4 -# This cop supports unsafe autocorrection (--autocorrect-all). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: literals, strict -Style/MutableConstant: - Exclude: - - 'lib/zendesk_api/client.rb' - - 'lib/zendesk_api/collection.rb' - - 'lib/zendesk_api/middleware/request/retry.rb' - - 'lib/zendesk_api/version.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: both, prefix, postfix -Style/NegatedIf: - Exclude: - - 'lib/zendesk_api/middleware/request/upload.rb' - -# Offense count: 5 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: Strict, AllowedNumbers, AllowedPatterns. -Style/NumericLiterals: - MinDigits: 11 - -# Offense count: 2 -# This cop supports unsafe autocorrection (--autocorrect-all). -# Configuration parameters: EnforcedStyle, AllowedMethods, AllowedPatterns. -# SupportedStyles: predicate, comparison -Style/NumericPredicate: - Exclude: - - 'spec/**/*' - - 'lib/zendesk_api/middleware/request/retry.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -Style/ParallelAssignment: - Exclude: - - 'lib/zendesk_api/collection.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: AllowSafeAssignment, AllowInMultilineConditions. -Style/ParenthesesAroundCondition: - Exclude: - - 'lib/zendesk_api/collection.rb' - -# Offense count: 21 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: PreferredDelimiters. -Style/PercentLiteralDelimiters: - Exclude: - - 'Rakefile' - - 'lib/zendesk_api/collection.rb' - - 'lib/zendesk_api/resources.rb' - - 'spec/core/collection_spec.rb' - - 'spec/core/middleware/request/etag_cache_spec.rb' - - 'spec/core/resource_spec.rb' - - 'spec/core/resources/view_spec.rb' - - 'spec/live/app_installation_spec.rb' - - 'spec/live/app_spec.rb' - - 'spec/live/push_notification_device_spec.rb' - - 'spec/live/tag_spec.rb' - - 'spec/live/ticket_spec.rb' - -# Offense count: 5 -# This cop supports safe autocorrection (--autocorrect). -Style/PerlBackrefs: - Exclude: - - 'lib/zendesk_api/helpers.rb' - -# Offense count: 6 -# This cop supports unsafe autocorrection (--autocorrect-all). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: short, verbose -Style/PreferredHashMethods: - Exclude: - - 'lib/zendesk_api/associations.rb' - - 'lib/zendesk_api/lru_cache.rb' - - 'lib/zendesk_api/track_changes.rb' - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -Style/Proc: - Exclude: - - 'spec/core/collection_spec.rb' - -# Offense count: 4 -# This cop supports unsafe autocorrection (--autocorrect-all). -# Configuration parameters: EnforcedStyle, AllowedCompactTypes. -# SupportedStyles: compact, exploded -Style/RaiseArgs: - Exclude: - - 'lib/zendesk_api/association.rb' - - 'lib/zendesk_api/middleware/response/raise_error.rb' - -# Offense count: 60 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle, AllowInnerSlashes. -# SupportedStyles: slashes, percent_r, mixed -Style/RegexpLiteral: - Exclude: - - 'lib/zendesk_api/helpers.rb' - - 'spec/core/client_spec.rb' - - 'spec/core/collection_spec.rb' - - 'spec/core/create_resource_spec.rb' - - 'spec/core/middleware/request/etag_cache_spec.rb' - - 'spec/core/middleware/request/retry_spec.rb' - - 'spec/core/middleware/response/callback_spec.rb' - - 'spec/core/middleware/response/deflate_spec.rb' - - 'spec/core/middleware/response/gzip_spec.rb' - - 'spec/core/middleware/response/parse_iso_dates_spec.rb' - - 'spec/core/middleware/response/parse_json_spec.rb' - - 'spec/core/resource_spec.rb' - -# Offense count: 6 -# This cop supports unsafe autocorrection (--autocorrect-all). -# Configuration parameters: ConvertCodeThatCanStartToReturnNil, AllowedMethods, MaxChainLength. -# AllowedMethods: present?, blank?, presence, try, try! -Style/SafeNavigation: - Exclude: - - 'lib/zendesk_api/association.rb' - - 'lib/zendesk_api/collection.rb' - - 'lib/zendesk_api/middleware/request/retry.rb' - -# Offense count: 5 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle. -# SupportedStyles: only_raise, only_fail, semantic -Style/SignalException: - Exclude: - - 'spec/core/middleware/response/raise_error_spec.rb' - - 'spec/live/app_installation_spec.rb' - - 'spec/live/app_spec.rb' - - 'spec/live/ticket_spec.rb' - -# Offense count: 1 -# This cop supports unsafe autocorrection (--autocorrect-all). -# Configuration parameters: RequireEnglish, EnforcedStyle. -# SupportedStyles: use_perl_names, use_english_names, use_builtin_english_names -Style/SpecialGlobalVars: - Exclude: - - 'spec/core/spec_helper.rb' - -# Offense count: 1742 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: EnforcedStyle, ConsistentQuotesInMultiline. -# SupportedStyles: single_quotes, double_quotes -Style/StringLiterals: - Enabled: false - -# Offense count: 5 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: MinSize. -# SupportedStyles: percent, brackets -Style/SymbolArray: - EnforcedStyle: brackets - -# Offense count: 61 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: AllowHeredoc, AllowURI, AllowQualifiedName, URISchemes, IgnoreCopDirectives, AllowedPatterns, SplitStrings. -# URISchemes: http, https -Layout/LineLength: - Max: 160 diff --git a/.standard_todo.yml b/.standard_todo.yml new file mode 100644 index 00000000..6acbc218 --- /dev/null +++ b/.standard_todo.yml @@ -0,0 +1,14 @@ +# Auto generated files with errors to ignore. +# Remove from this list as you refactor files. +--- +ignore: +- lib/zendesk_api/client.rb: + - Style/MissingRespondToMissing +- lib/zendesk_api/resource.rb: + - Style/TrivialAccessors +- spec/core/collection_spec.rb: + - Lint/ConstantDefinitionInBlock +- spec/core/resource_spec.rb: + - Lint/ConstantDefinitionInBlock +- spec/core/spec_helper.rb: + - Style/GlobalVars diff --git a/Gemfile b/Gemfile index 06fc3cd1..decf4f88 100644 --- a/Gemfile +++ b/Gemfile @@ -1,4 +1,4 @@ -source 'https://rubygems.org' +source "https://rubygems.org" gem "jruby-openssl", platforms: :jruby gem "mini_mime" @@ -8,7 +8,7 @@ gem "yard" gem "json", ">= 2.3.0", platforms: :ruby gem "scrub_rb" -gem "rubocop" +gem "standard" group :test do gem "webmock" diff --git a/Gemfile.lock b/Gemfile.lock index c84ef6cd..94973f08 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -91,13 +91,19 @@ GEM nokogiri (1.18.9) mini_portile2 (~> 2.8.2) racc (~> 1.4) + nokogiri (1.18.9-aarch64-linux-gnu) + racc (~> 1.4) + nokogiri (1.18.9-arm64-darwin) + racc (~> 1.4) nokogiri (1.18.9-java) racc (~> 1.4) + nokogiri (1.18.9-x86_64-linux-gnu) + racc (~> 1.4) parallel (1.27.0) - parser (3.3.9.0) + parser (3.3.10.0) ast (~> 2.4.1) racc - prism (1.4.0) + prism (1.6.0) public_suffix (6.0.2) racc (1.8.1) racc (1.8.1-java) @@ -116,7 +122,7 @@ GEM nokogiri (>= 1.15.7, != 1.16.7, != 1.16.6, != 1.16.5, != 1.16.4, != 1.16.3, != 1.16.2, != 1.16.1, != 1.16.0.rc1, != 1.16.0) rainbow (3.1.1) rake (13.3.0) - regexp_parser (2.11.1) + regexp_parser (2.11.3) rexml (3.4.1) rspec (3.10.0) rspec-core (~> 3.10.0) @@ -131,7 +137,7 @@ GEM diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.10.0) rspec-support (3.10.3) - rubocop (1.79.2) + rubocop (1.80.2) json (~> 2.3) language_server-protocol (~> 3.17.0.2) lint_roller (~> 1.1.0) @@ -142,17 +148,33 @@ GEM rubocop-ast (>= 1.46.0, < 2.0) ruby-progressbar (~> 1.7) unicode-display_width (>= 2.4.0, < 4.0) - rubocop-ast (1.46.0) + rubocop-ast (1.47.1) parser (>= 3.3.7.2) prism (~> 1.4) + rubocop-performance (1.25.0) + lint_roller (~> 1.1) + rubocop (>= 1.75.0, < 2.0) + rubocop-ast (>= 1.38.0, < 2.0) ruby-progressbar (1.13.0) scrub_rb (1.0.1) securerandom (0.4.1) + standard (1.51.1) + language_server-protocol (~> 3.17.0.2) + lint_roller (~> 1.0) + rubocop (~> 1.80.2) + standard-custom (~> 1.0.0) + standard-performance (~> 1.8) + standard-custom (1.0.2) + lint_roller (~> 1.0) + rubocop (~> 1.50) + standard-performance (1.8.0) + lint_roller (~> 1.1) + rubocop-performance (~> 1.25.0) tzinfo (2.0.6) concurrent-ruby (~> 1.0) - unicode-display_width (3.1.4) - unicode-emoji (~> 4.0, >= 4.0.4) - unicode-emoji (4.0.4) + unicode-display_width (3.2.0) + unicode-emoji (~> 4.1) + unicode-emoji (4.1.0) uri (1.0.3) useragent (0.16.11) vcr (6.3.1) @@ -164,8 +186,11 @@ GEM yard (0.9.37) PLATFORMS + aarch64-linux + arm64-darwin java ruby + x86_64-linux DEPENDENCIES actionpack (>= 5.2.4.6) @@ -181,8 +206,8 @@ DEPENDENCIES rspec-expectations (= 3.10.2) rspec-mocks (= 3.10.2) rspec-support (= 3.10.3) - rubocop scrub_rb + standard vcr (~> 6.0) webmock yard diff --git a/Rakefile b/Rakefile index 89f66011..3ec30310 100644 --- a/Rakefile +++ b/Rakefile @@ -1,11 +1,11 @@ -require 'bundler/setup' -require 'rake/testtask' -require 'bundler/gem_tasks' -require 'bump/tasks' -require 'rubocop/rake_task' +require "bundler/setup" +require "rake/testtask" +require "bundler/gem_tasks" +require "bump/tasks" +require "standard/rake" begin - require 'rspec/core/rake_task' + require "rspec/core/rake_task" rescue LoadError puts "WARN: #{$ERROR_INFO.message} Continuing..." end @@ -32,22 +32,22 @@ if defined?(RSpec) .sub("your_zendesk_host", ENV.fetch("SPEC_LIVE_ZENDESK_HOST"))) end - desc 'Default: run specs.' - task :default => "spec" + desc "Default: run specs." + task default: "spec" end # extracted from https://github.com/grosser/project_template rule(/^version:bump:.*/) do |t| sh "git status | grep 'nothing to commit'" # ensure we are not dirty - index = %w(major minor patch).index(t.name.split(':').last) - file = 'lib/zendesk_api/version.rb' + index = %w[major minor patch].index(t.name.split(":").last) + file = "lib/zendesk_api/version.rb" version_file = File.read(file) old_version, *version_parts = version_file.match(/(\d+)\.(\d+)\.(\d+)/).to_a version_parts[index] = version_parts[index].to_i + 1 version_parts[2] = 0 if index < 2 # remove patch for minor version_parts[1] = 0 if index < 1 # remove minor for major - new_version = version_parts * '.' + new_version = version_parts * "." File.write(file, version_file.sub(old_version, new_version)) sh "bundle && git add #{file} Gemfile.lock && git commit -m 'bump version to #{new_version}'" diff --git a/lib/zendesk_api.rb b/lib/zendesk_api.rb index 7c9e262a..c8ebe13d 100644 --- a/lib/zendesk_api.rb +++ b/lib/zendesk_api.rb @@ -1,8 +1,8 @@ module ZendeskAPI; end -require 'faraday' -require 'faraday/multipart' +require "faraday" +require "faraday/multipart" -require 'zendesk_api/helpers' -require 'zendesk_api/core_ext/inflection' -require 'zendesk_api/client' +require_relative "zendesk_api/helpers" +require_relative "zendesk_api/core_ext/inflection" +require_relative "zendesk_api/client" diff --git a/lib/zendesk_api/actions.rb b/lib/zendesk_api/actions.rb index 91c712fe..0bc4d9fc 100644 --- a/lib/zendesk_api/actions.rb +++ b/lib/zendesk_api/actions.rb @@ -66,7 +66,7 @@ def save_associations self.class.associations.each do |association_data| association_name = association_data[:name] - next unless send("#{association_name}_used?") && association = send(association_name) + next unless send("#{association_name}_used?") && (association = send(association_name)) inline_creation = association_data[:inline] == :create && new_record? changed = association.is_a?(Collection) || association.changed? @@ -110,7 +110,7 @@ def find!(client, options = {}) @client = client # so we can use client.logger in rescue raise ArgumentError, "No :id given" unless options[:id] || options["id"] || ancestors.include?(SingularResource) - association = options.delete(:association) || Association.new(:class => self) + association = options.delete(:association) || Association.new(class: self) includes = Array(options[:include]) options[:include] = includes.join(",") if includes.any? @@ -170,9 +170,9 @@ module CreateMany # @param [Client] client The {Client} object to be used # @param [Array] attributes_array An array of resources to be created. # @return [JobStatus] the {JobStatus} instance for this create job - def create_many!(client, attributes_array, association = Association.new(:class => self)) + def create_many!(client, attributes_array, association = Association.new(class: self)) response = client.connection.post("#{association.generate_path}/create_many") do |req| - req.body = { resource_name => attributes_array } + req.body = {resource_name => attributes_array} yield req if block_given? end @@ -185,9 +185,9 @@ module CreateOrUpdate # Creates or updates resource using the create_or_update endpoint. # @param [Client] client The {Client} object to be used # @param [Hash] attributes The attributes to create. - def create_or_update!(client, attributes, association = Association.new(:class => self)) + def create_or_update!(client, attributes, association = Association.new(class: self)) response = client.connection.post("#{association.generate_path}/create_or_update") do |req| - req.body = { singular_resource_name => attributes } + req.body = {singular_resource_name => attributes} yield req if block_given? end @@ -204,10 +204,10 @@ module CreateOrUpdateMany # # @return [JobStatus] the {JobStatus} instance for this destroy job def create_or_update_many!(client, attributes) - association = Association.new(:class => self) + association = Association.new(class: self) response = client.connection.post("#{association.generate_path}/create_or_update_many") do |req| - req.body = { resource_name => attributes } + req.body = {resource_name => attributes} yield req if block_given? end @@ -269,9 +269,9 @@ module DestroyMany # @param [Client] client The {Client} object to be used # @param [Array] ids An array of ids to destroy # @return [JobStatus] the {JobStatus} instance for this destroy job - def destroy_many!(client, ids, association = Association.new(:class => self)) + def destroy_many!(client, ids, association = Association.new(class: self)) response = client.connection.delete("#{association.generate_path}/destroy_many") do |req| - req.params = { :ids => ids.join(',') } + req.params = {ids: ids.join(",")} yield req if block_given? end @@ -300,9 +300,9 @@ def update(client, attributes = {}, &) # @param [Hash] attributes The attributes to update. Default to { def update!(client, attributes = {}, &) ZendeskAPI::Client.check_deprecated_namespace_usage attributes, singular_resource_name - resource = new(client, :id => attributes.delete(:id), :global => attributes.delete(:global), :association => attributes.delete(:association)) + resource = new(client, id: attributes.delete(:id), global: attributes.delete(:global), association: attributes.delete(:association)) resource.attributes.merge!(attributes) - resource.save!(:force_update => resource.is_a?(SingularResource), &) + resource.save!(force_update: resource.is_a?(SingularResource), &) resource end end @@ -315,14 +315,14 @@ module UpdateMany # @param [Hash] attributes The attributes to update resources with # @return [JobStatus] the {JobStatus} instance for this destroy job def update_many!(client, ids_or_attributes, attributes = {}) - association = attributes.delete(:association) || Association.new(:class => self) + association = attributes.delete(:association) || Association.new(class: self) response = client.connection.put("#{association.generate_path}/update_many") do |req| if attributes == {} - req.body = { resource_name => ids_or_attributes } + req.body = {resource_name => ids_or_attributes} else - req.params = { :ids => ids_or_attributes.join(',') } - req.body = { singular_resource_name => attributes } + req.params = {ids: ids_or_attributes.join(",")} + req.body = {singular_resource_name => attributes} end yield req if block_given? diff --git a/lib/zendesk_api/association.rb b/lib/zendesk_api/association.rb index 9ae5efb3..e1fd44ab 100644 --- a/lib/zendesk_api/association.rb +++ b/lib/zendesk_api/association.rb @@ -1,4 +1,4 @@ -require 'zendesk_api/helpers' +require_relative "helpers" module ZendeskAPI # Represents an association between two resources @@ -43,7 +43,7 @@ def initialize(options = {}) # * with_parent - Include the parent path (false by default) # * with_id - Include the instance id, if possible (true) def generate_path(*args) - options = SilentMash.new(:with_id => true) + options = SilentMash.new(with_id: true) if args.last.is_a?(Hash) original_options = args.pop options.merge!(original_options) @@ -66,7 +66,7 @@ def generate_path(*args) namespace[0] = @options.path || @options[:class].resource_path end - if id = extract_id(instance, options, original_options) + if (id = extract_id(instance, options, original_options)) namespace << id end @@ -93,7 +93,7 @@ def side_load(resources, side_loads) # @return [Array] ['ZendeskAPI', 'Voice', etc.. ] def ignorable_namespace_strings - ZendeskAPI::DataNamespace.descendants.map { |klass| klass.to_s.split('::') }.flatten.uniq + ZendeskAPI::DataNamespace.descendants.map { |klass| klass.to_s.split("::") }.flatten.uniq end def _side_load(resource, side_loads) @@ -106,10 +106,10 @@ def _side_load(resource, side_loads) end end - def side_load_from_parent_id(resource, side_loads, key) + def side_load_from_parent_id(resource, side_loads, _key) key = "#{resource.class.singular_resource_name}_id" - resource.send("#{options.name}=", _side_load(resource, side_loads.select {|side_load| + resource.send("#{options.name}=", _side_load(resource, side_loads.select { |side_load| side_load[key] == resource.id })) end @@ -117,7 +117,7 @@ def side_load_from_parent_id(resource, side_loads, key) def side_load_from_child_ids(resource, side_loads, plural_key) ids = resource.send(plural_key) - resource.send("#{options.name}=", _side_load(resource, side_loads.select {|side_load| + resource.send("#{options.name}=", _side_load(resource, side_loads.select { |side_load| ids.include?(side_load[options.include_key]) })) end @@ -178,7 +178,7 @@ def extract_parent_id(parent_class, instance, options, original_options) def extract_id(instance, options, original_options) if options[:with_id] && !@options[:class].ancestors.include?(SingularResource) - if instance && instance.id + if instance&.id instance.id elsif options[:id] original_options.delete(:id) || original_options.delete("id") diff --git a/lib/zendesk_api/associations.rb b/lib/zendesk_api/associations.rb index 8ec8b015..c8b9b2d2 100644 --- a/lib/zendesk_api/associations.rb +++ b/lib/zendesk_api/associations.rb @@ -1,4 +1,4 @@ -require 'zendesk_api/helpers' +require_relative "helpers" module ZendeskAPI # This module holds association method for resources. @@ -14,12 +14,12 @@ def self.included(base) end def wrap_resource(resource, class_level_association, options = {}) - instance_association = Association.new(class_level_association.merge(:parent => self)) + instance_association = Association.new(class_level_association.merge(parent: self)) klass = class_level_association[:class] case resource when Hash - klass.new(@client, resource.merge(:association => instance_association)) + klass.new(@client, resource.merge(association: instance_association)) when String, Integer klass.new(@client, options[:include_key] || :id => resource, :association => instance_association) else @@ -40,12 +40,10 @@ def associations end def associated_with(name) - associations.inject([]) do |associated_with, association| + associations.each_with_object([]) do |association, associated_with| if association[:include] == name.to_s associated_with.push(Association.new(association)) end - - associated_with end end @@ -53,14 +51,14 @@ def associated_with(name) def build_association(klass, resource_name, options) { - :class => klass, - :name => resource_name, - :inline => options.delete(:inline), - :path => options.delete(:path), - :include => (options.delete(:include) || klass.resource_name).to_s, - :include_key => (options.delete(:include_key) || :id).to_s, - :singular => options.delete(:singular), - :extensions => Array(options.delete(:extend)) + class: klass, + name: resource_name, + inline: options.delete(:inline), + path: options.delete(:path), + include: (options.delete(:include) || klass.resource_name).to_s, + include_key: (options.delete(:include_key) || :id).to_s, + singular: options.delete(:singular), + extensions: Array(options.delete(:extend)) } end @@ -75,7 +73,7 @@ module Has # @param [Symbol] resource_name_or_class The underlying resource name or a class to get it from # @param [Hash] class_level_options The options to pass to the method definition. def has(resource_name_or_class, class_level_options = {}) - if klass = class_level_options.delete(:class) + if (klass = class_level_options.delete(:class)) resource_name = resource_name_or_class else klass = resource_name_or_class @@ -83,7 +81,8 @@ def has(resource_name_or_class, class_level_options = {}) end class_level_association = build_association(klass, resource_name, class_level_options) - class_level_association.merge!(:singular => true, :id_column => "#{resource_name}_id") + class_level_association[:singular] = true + class_level_association[:id_column] = "#{resource_name}_id" associations << class_level_association @@ -105,14 +104,14 @@ def define_has_getter(association) return cached if cached && !instance_options[:reload] # find and cache association - instance_association = Association.new(association.merge(:parent => self)) - resource = if klass.respond_to?(:find) && resource_id = method_missing(association[:id_column]) - klass.find(@client, :id => resource_id, :association => instance_association) - elsif found = method_missing(association[:name].to_sym) - wrap_resource(found, association, :include_key => association[:include_key]) + instance_association = Association.new(association.merge(parent: self)) + resource = if klass.respond_to?(:find) && (resource_id = method_missing(association[:id_column])) + klass.find(@client, id: resource_id, association: instance_association) + elsif (found = method_missing(association[:name].to_sym)) + wrap_resource(found, association, include_key: association[:include_key]) elsif klass.superclass == DataResource && !association[:inline] - response = @client.connection.get(instance_association.generate_path(:with_parent => true)) - klass.new(@client, response.body[klass.singular_resource_name].merge(:association => instance_association)) + response = @client.connection.get(instance_association.generate_path(with_parent: true)) + klass.new(@client, response.body[klass.singular_resource_name].merge(association: instance_association)) end send("#{association[:id_column]}=", resource.id) if resource && has_key?(association[:id_column]) @@ -134,7 +133,7 @@ module HasMany # @param [Symbol] resource_name_or_class The underlying resource name or class to get it from # @param [Hash] class_level_options The options to pass to the method definition. def has_many(resource_name_or_class, class_level_options = {}) - if klass = class_level_options.delete(:class) + if (klass = class_level_options.delete(:class)) resource_name = resource_name_or_class else klass = resource_name_or_class @@ -142,7 +141,8 @@ def has_many(resource_name_or_class, class_level_options = {}) end class_level_association = build_association(klass, resource_name, class_level_options) - class_level_association.merge!(:singular => false, :id_column => "#{resource_name}_ids") + class_level_association[:singular] = false + class_level_association[:id_column] = "#{resource_name}_ids" associations << class_level_association @@ -164,12 +164,12 @@ def define_has_many_getter(association) return cached if cached && !instance_opts[:reload] # find and cache association - instance_association = Association.new(association.merge(:parent => self)) + instance_association = Association.new(association.merge(parent: self)) singular_resource_name = Inflection.singular(association[:name].to_s) resources = if (ids = method_missing("#{singular_resource_name}_ids")) && ids.any? ids.map do |id| - klass.find(@client, :id => id, :association => instance_association) + klass.find(@client, id: id, association: instance_association) end.compact elsif (resources = method_missing(association[:name].to_sym)) && resources.any? resources.map { |res| wrap_resource(res, association) } @@ -177,7 +177,7 @@ def define_has_many_getter(association) [] end - collection = ZendeskAPI::Collection.new(@client, klass, instance_opts.merge(:association => instance_association)) + collection = ZendeskAPI::Collection.new(@client, klass, instance_opts.merge(association: instance_association)) if association[:extensions].any? collection.extend(*association[:extensions]) @@ -198,7 +198,7 @@ def define_has_many_setter(association) wrapped = resources.map { |attr| wrap_resource(attr, association) } send(association[:name]).replace(wrapped) else - resources.association = Association.new(association.merge(:parent => self)) + resources.association = Association.new(association.merge(parent: self)) instance_variable_set("@#{association[:name]}", resources) end diff --git a/lib/zendesk_api/client.rb b/lib/zendesk_api/client.rb index 2b9775bc..57e41808 100644 --- a/lib/zendesk_api/client.rb +++ b/lib/zendesk_api/client.rb @@ -1,25 +1,25 @@ -require 'zendesk_api/version' -require 'zendesk_api/sideloading' -require 'zendesk_api/configuration' -require 'zendesk_api/collection' -require 'zendesk_api/lru_cache' -require 'zendesk_api/silent_mash' -require 'zendesk_api/middleware/request/etag_cache' -require 'zendesk_api/middleware/request/retry' -require 'zendesk_api/middleware/request/raise_rate_limited' -require 'zendesk_api/middleware/request/upload' -require 'zendesk_api/middleware/request/encode_json' -require 'zendesk_api/middleware/request/api_token_impersonate' -require 'zendesk_api/middleware/request/url_based_access_token' -require 'zendesk_api/middleware/response/callback' -require 'zendesk_api/middleware/response/deflate' -require 'zendesk_api/middleware/response/gzip' -require 'zendesk_api/middleware/response/sanitize_response' -require 'zendesk_api/middleware/response/parse_iso_dates' -require 'zendesk_api/middleware/response/parse_json' -require 'zendesk_api/middleware/response/raise_error' -require 'zendesk_api/middleware/response/logger' -require 'zendesk_api/delegator' +require_relative "version" +require_relative "sideloading" +require_relative "configuration" +require_relative "collection" +require_relative "lru_cache" +require_relative "silent_mash" +require_relative "middleware/request/etag_cache" +require_relative "middleware/request/retry" +require_relative "middleware/request/raise_rate_limited" +require_relative "middleware/request/upload" +require_relative "middleware/request/encode_json" +require_relative "middleware/request/api_token_impersonate" +require_relative "middleware/request/url_based_access_token" +require_relative "middleware/response/callback" +require_relative "middleware/response/deflate" +require_relative "middleware/response/gzip" +require_relative "middleware/response/sanitize_response" +require_relative "middleware/response/parse_iso_dates" +require_relative "middleware/response/parse_json" +require_relative "middleware/response/raise_error" +require_relative "middleware/response/logger" +require_relative "delegator" module ZendeskAPI # The top-level class that handles configuration and connection to the Zendesk API. @@ -44,7 +44,7 @@ def method_missing(method, *args, &) return ZendeskAPI::Collection.new(self, resource_class, options) end - @resource_cache[method] ||= { :class => nil, :cache => ZendeskAPI::LRUCache.new } + @resource_cache[method] ||= {class: nil, cache: ZendeskAPI::LRUCache.new} if !options.delete(:reload) && (cached = @resource_cache[method][:cache].read(options.hash)) cached else @@ -63,21 +63,21 @@ def respond_to?(method, *args) # @return [ZendeskAPI::User] Current user or nil def current_user(reload = false) return @current_user if @current_user && !reload - @current_user = users.find(:id => 'me') + @current_user = users.find(id: "me") end # Returns the current account # @return [Hash] The attributes of the current account or nil def current_account(reload = false) return @current_account if @current_account && !reload - @current_account = SilentMash.new(connection.get('account/resolve').body) + @current_account = SilentMash.new(connection.get("account/resolve").body) end # Returns the current locale # @return [ZendeskAPI::Locale] Current locale or nil def current_locale(reload = false) return @locale if @locale && !reload - @locale = locales.find(:id => 'current') + @locale = locales.find(id: "current") end # Creates a new {Client} instance and yields {#config}. @@ -181,7 +181,7 @@ def build_connection set_authentication(builder, config) if config.cache - builder.use ZendeskAPI::Middleware::Request::EtagCache, :cache => config.cache + builder.use ZendeskAPI::Middleware::Request::EtagCache, cache: config.cache end builder.use ZendeskAPI::Middleware::Request::Upload @@ -191,12 +191,12 @@ def build_connection # Should always be first in the stack if config.retry builder.use ZendeskAPI::Middleware::Request::Retry, - :logger => config.logger, - :retry_codes => config.retry_codes, - :retry_on_exception => config.retry_on_exception + logger: config.logger, + retry_codes: config.retry_codes, + retry_on_exception: config.retry_on_exception end if config.raise_error_when_rate_limited - builder.use ZendeskAPI::Middleware::Request::RaiseRateLimited, :logger => config.logger + builder.use ZendeskAPI::Middleware::Request::RaiseRateLimited, logger: config.logger end builder.adapter(*adapter, &config.adapter_proc) @@ -207,12 +207,12 @@ def build_connection private def resource_class_for(method) - resource_name = ZendeskAPI::Helpers.modulize_string(Inflection.singular(method.to_s.gsub(/\W/, ''))) + resource_name = ZendeskAPI::Helpers.modulize_string(Inflection.singular(method.to_s.gsub(/\W/, ""))) ZendeskAPI::Association.class_from_namespace(resource_name) end def check_url - if !config.allow_http && !config.url.start_with?('https://') + if !config.allow_http && !config.url.start_with?("https://") raise ArgumentError, "zendesk_api is ssl only; url must begin with https://" end end @@ -238,17 +238,17 @@ def set_token_auth def set_default_logger if config.logger.nil? || config.logger == true - require 'logger' + require "logger" config.logger = Logger.new($stderr) config.logger.level = Logger::WARN end end def add_warning_callback - return unless logger = config.logger + return unless (logger = config.logger) insert_callback do |env| - if warning = env[:response_headers]["X-Zendesk-API-Warn"] + if (warning = env[:response_headers]["X-Zendesk-API-Warn"]) logger.warn "WARNING: #{warning}" end end diff --git a/lib/zendesk_api/collection.rb b/lib/zendesk_api/collection.rb index 3848c1c3..545633e5 100644 --- a/lib/zendesk_api/collection.rb +++ b/lib/zendesk_api/collection.rb @@ -1,7 +1,7 @@ -require 'zendesk_api/resource' -require 'zendesk_api/resources' -require 'zendesk_api/search' -require 'zendesk_api/pagination' +require_relative "resource" +require_relative "resources" +require_relative "search" +require_relative "pagination" module ZendeskAPI # Represents a collection of resources. Lazily loaded, resources aren't @@ -50,7 +50,7 @@ def initialize(client, resource, options = {}) end # Methods that take a Hash argument - methods = %w{create find update update_many destroy create_or_update} + methods = %w[create find update update_many destroy create_or_update] methods += methods.map { |method| "#{method}!" } methods.each do |deferrable| # Passes arguments and the proper path to the resource class method. @@ -61,14 +61,14 @@ def initialize(client, resource, options = {}) end args << {} unless args.last.is_a?(Hash) - args.last.merge!(:association => @association) + args.last[:association] = @association @resource_class.send(deferrable, @client, *args) end end # Methods that take an Array argument - methods = %w{create_many! destroy_many!} + methods = %w[create_many! destroy_many!] methods.each do |deferrable| # Passes arguments and the proper path to the resource class method. # @param [Array] array arguments @@ -153,7 +153,7 @@ def <<(item) # The API path to this collection def path - @association.generate_path(:with_parent => true) + @association.generate_path(with_parent: true) end # Executes actual GET from API and loads resources into proper class. @@ -161,7 +161,7 @@ def path def fetch!(reload = false) if @resources && (!@fetchable || !reload) return @resources - elsif association && association.options.parent && association.options.parent.new_record? + elsif association&.options&.parent&.new_record? return (@resources = []) end @@ -289,11 +289,11 @@ def to_s inspect = [] inspect << "options=#{@options.inspect}" if @options.any? inspect << "path=#{path}" - "#{Inflection.singular(@resource)} collection [#{inspect.join(',')}]" + "#{Inflection.singular(@resource)} collection [#{inspect.join(",")}]" end end - alias to_str to_s + alias_method :to_str, :to_s def to_param map(&:to_param) @@ -303,7 +303,7 @@ def get_next_page_data(original_response_body) link = original_response_body["links"]["next"] result_key = @resource_class.model_key || "results" while link - response = @client.connection.send("get", link).body + response = @client.connection.send(:get, link).body original_response_body[result_key] = original_response_body[result_key] + response[result_key] @@ -338,7 +338,7 @@ def _all(start_page = @options["page"], bang = false, &block) page(start_page) clear_cache - while (bang ? fetch! : fetch) + while bang ? fetch! : fetch each do |resource| block.call(resource, @options["page"] || 1) end @@ -370,7 +370,7 @@ def join_special_params # some params use comma-joined strings instead of query-based arrays for multiple values @options.each do |k, v| if SPECIALLY_JOINED_PARAMS.include?(k.to_sym) && v.is_a?(Array) - @options[k] = v.join(',') + @options[k] = v.join(",") end end end @@ -378,9 +378,9 @@ def join_special_params def set_association_from_options @collection_path = @options.delete(:collection_path) - association_options = { :path => @options.delete(:path) } + association_options = {path: @options.delete(:path)} association_options[:path] ||= @collection_path.join("/") if @collection_path - @association = @options.delete(:association) || Association.new(association_options.merge(:class => @resource_class)) + @association = @options.delete(:association) || Association.new(association_options.merge(class: @resource_class)) @collection_path ||= [@resource] end @@ -389,9 +389,9 @@ def get_response(path) @client.connection.send(@verb || "get", path) do |req| opts = @options.delete_if { |_, v| v.nil? } - req.params.merge!(:include => @includes.join(",")) if @includes.any? + req.params[:include] = @includes.join(",") if @includes.any? - if %w{put post}.include?(@verb.to_s) + if %w[put post].include?(@verb.to_s) req.body = opts else req.params.merge!(opts) @@ -440,11 +440,11 @@ def wrap_resource(res, with_association = with_association?) when Array wrap_resource(Hash[*res], with_association) when Hash - res = res.merge(:association => @association) if with_association + res = res.merge(association: @association) if with_association @resource_class.new(@client, res) else - res = { :id => res } - res.merge!(:association => @association) if with_association + res = {id: res} + res[:association] = @association if with_association @resource_class.new(@client, res) end end @@ -464,7 +464,8 @@ def array_method(name, ...) # If you call client.tickets.foo - and foo is not an attribute nor an association, it ends up here, as a new collection def next_collection(name, *args, &) opts = args.last.is_a?(Hash) ? args.last : {} - opts.merge!(collection_path: [*@collection_path, name], page: nil) + opts[:collection_path] = [*@collection_path, name] + opts[:page] = nil # Why `page: nil`? # when you do client.tickets.fetch followed by client.tickets.foos => the request to /tickets/foos will # have the options page set to whatever the last options were for the tickets collection diff --git a/lib/zendesk_api/configuration.rb b/lib/zendesk_api/configuration.rb index 4f34df73..bf8d27af 100644 --- a/lib/zendesk_api/configuration.rb +++ b/lib/zendesk_api/configuration.rb @@ -66,16 +66,16 @@ def initialize # @return [Hash] Faraday-formatted hash of options. def options { - :headers => { - :accept => 'application/json', - :accept_encoding => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - :user_agent => "ZendeskAPI Ruby #{ZendeskAPI::VERSION}" + headers: { + accept: "application/json", + accept_encoding: "gzip;q=1.0,deflate;q=0.6,identity;q=0.3", + user_agent: "ZendeskAPI Ruby #{ZendeskAPI::VERSION}" }, - :request => { - :open_timeout => 10, - :timeout => 60 + request: { + open_timeout: 10, + timeout: 60 }, - :url => @url + url: @url }.merge(client_options) end end diff --git a/lib/zendesk_api/core_ext/inflection.rb b/lib/zendesk_api/core_ext/inflection.rb index 1634735a..cbb7a87a 100644 --- a/lib/zendesk_api/core_ext/inflection.rb +++ b/lib/zendesk_api/core_ext/inflection.rb @@ -1,3 +1,3 @@ -require 'inflection' +require "inflection" -Inflection.plural_rule 'forum', 'forums' +Inflection.plural_rule "forum", "forums" diff --git a/lib/zendesk_api/delegator.rb b/lib/zendesk_api/delegator.rb index 59d1adf7..2770584c 100644 --- a/lib/zendesk_api/delegator.rb +++ b/lib/zendesk_api/delegator.rb @@ -1,4 +1,4 @@ -require 'delegate' +require "delegate" module ZendeskAPI class Delegator < SimpleDelegator; end diff --git a/lib/zendesk_api/helpers.rb b/lib/zendesk_api/helpers.rb index b262eb54..836aae68 100644 --- a/lib/zendesk_api/helpers.rb +++ b/lib/zendesk_api/helpers.rb @@ -21,10 +21,10 @@ def self.present?(value) # @return [string] a string that can become a class, `Module::ClassName` def self.modulize_string(string) # gsub('__','/'). # why was this ever here? - string.gsub(/__(.?)/) { "::#{$1.upcase}" }. - gsub(/\/(.?)/) { "::#{$1.upcase}" }. - gsub(/(?:_+|-+)([a-z])/) { $1.upcase }. - gsub(/(\A|\s)([a-z])/) { $1 + $2.upcase } + string.gsub(/__(.?)/) { "::#{$1.upcase}" } + .gsub(/\/(.?)/) { "::#{$1.upcase}" } + .gsub(/(?:_+|-+)([a-z])/) { $1.upcase } + .gsub(/(\A|\s)([a-z])/) { $1 + $2.upcase } end # From https://github.com/rubyworks/facets/blob/master/lib/core/facets/string/snakecase.rb @@ -38,12 +38,12 @@ def self.modulize_string(string) # "Snake - Case".snakecase #=> "snake_case" def self.snakecase_string(string) # gsub(/::/, '/'). - string.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2'). - gsub(/([a-z\d])([A-Z])/, '\1_\2'). - tr('-', '_'). - gsub(/\s/, '_'). - gsub(/__+/, '_'). - downcase + string.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2') + .gsub(/([a-z\d])([A-Z])/, '\1_\2') + .tr("-", "_") + .gsub(/\s/, "_") + .gsub(/__+/, "_") + .downcase end end end diff --git a/lib/zendesk_api/middleware/request/api_token_impersonate.rb b/lib/zendesk_api/middleware/request/api_token_impersonate.rb index 49f54e54..20f079cb 100644 --- a/lib/zendesk_api/middleware/request/api_token_impersonate.rb +++ b/lib/zendesk_api/middleware/request/api_token_impersonate.rb @@ -1,4 +1,5 @@ -require 'base64' +require "base64" + module ZendeskAPI # @private module Middleware diff --git a/lib/zendesk_api/middleware/request/encode_json.rb b/lib/zendesk_api/middleware/request/encode_json.rb index 5384a418..32ebe7f2 100644 --- a/lib/zendesk_api/middleware/request/encode_json.rb +++ b/lib/zendesk_api/middleware/request/encode_json.rb @@ -4,13 +4,12 @@ module Middleware # @private module Request class EncodeJson < Faraday::Middleware - CONTENT_TYPE = 'Content-Type'.freeze - MIME_TYPE = 'application/json'.freeze + CONTENT_TYPE = "Content-Type".freeze + MIME_TYPE = "application/json".freeze def call(env) type = env[:request_headers][CONTENT_TYPE].to_s - type = type.split(';', 2).first if type.index(';') - type + type = type.split(";", 2).first if type.index(";") if env[:body] && !(env[:body].respond_to?(:to_str) && env[:body].empty?) && (type.empty? || type == MIME_TYPE) env[:body] = JSON.dump(env[:body]) diff --git a/lib/zendesk_api/middleware/request/etag_cache.rb b/lib/zendesk_api/middleware/request/etag_cache.rb index fef6c856..318a5147 100644 --- a/lib/zendesk_api/middleware/request/etag_cache.rb +++ b/lib/zendesk_api/middleware/request/etag_cache.rb @@ -36,10 +36,10 @@ def call(environment) env[:response_body] = cached[:response_body] env[:response_headers].merge!( - :etag => cached[:response_headers][:etag], - :content_type => cached[:response_headers][:content_type], - :content_length => cached[:response_headers][:content_length], - :content_encoding => cached[:response_headers][:content_encoding] + etag: cached[:response_headers][:etag], + content_type: cached[:response_headers][:content_type], + content_length: cached[:response_headers][:content_length], + content_encoding: cached[:response_headers][:content_encoding] ) elsif env[:status] == 200 && env[:response_headers]["Etag"] # modified and cacheable @cache.write(cache_key(env), env.to_hash) diff --git a/lib/zendesk_api/middleware/request/raise_rate_limited.rb b/lib/zendesk_api/middleware/request/raise_rate_limited.rb index 9feb817f..c720a67d 100644 --- a/lib/zendesk_api/middleware/request/raise_rate_limited.rb +++ b/lib/zendesk_api/middleware/request/raise_rate_limited.rb @@ -1,5 +1,5 @@ -require 'faraday/middleware' -require 'zendesk_api/error' +require "faraday/middleware" +require_relative "../../error" module ZendeskAPI module Middleware @@ -19,7 +19,7 @@ def call(env) response = @app.call(env) if ERROR_CODES.include?(response.env[:status]) - @logger&.warn 'You have been rate limited. Raising error...' + @logger&.warn "You have been rate limited. Raising error..." raise Error::RateLimited, env else response diff --git a/lib/zendesk_api/middleware/request/retry.rb b/lib/zendesk_api/middleware/request/retry.rb index 49932bcf..206519f0 100644 --- a/lib/zendesk_api/middleware/request/retry.rb +++ b/lib/zendesk_api/middleware/request/retry.rb @@ -1,4 +1,5 @@ require "faraday/middleware" + module ZendeskAPI module Middleware # @private @@ -12,8 +13,8 @@ class Retry < Faraday::Middleware def initialize(app, options = {}) super(app) @logger = options[:logger] - @error_codes = options.key?(:retry_codes) && options[:retry_codes] ? options[:retry_codes] : DEFAULT_ERROR_CODES - @retry_on_exception = options.key?(:retry_on_exception) && options[:retry_on_exception] ? options[:retry_on_exception] : false + @error_codes = (options.key?(:retry_codes) && options[:retry_codes]) ? options[:retry_codes] : DEFAULT_ERROR_CODES + @retry_on_exception = (options.key?(:retry_on_exception) && options[:retry_on_exception]) ? options[:retry_on_exception] : false end def call(env) @@ -22,7 +23,7 @@ def call(env) if @retry_on_exception begin response = @app.call(env) - rescue StandardError => e + rescue => e exception_happened = true end else @@ -33,20 +34,20 @@ def call(env) if exception_happened seconds_left = DEFAULT_RETRY_AFTER.to_i - @logger.warn "An exception happened, waiting #{seconds_left} seconds... #{e}" if @logger + @logger&.warn "An exception happened, waiting #{seconds_left} seconds... #{e}" else seconds_left = (response.env[:response_headers][:retry_after] || DEFAULT_RETRY_AFTER).to_i end - @logger.warn "You have been rate limited. Retrying in #{seconds_left} seconds..." if @logger + @logger&.warn "You have been rate limited. Retrying in #{seconds_left} seconds..." seconds_left.times do |i| sleep 1 time_left = seconds_left - i - @logger.warn "#{time_left}..." if time_left > 0 && time_left % 5 == 0 && @logger + @logger&.warn "#{time_left}..." if time_left > 0 && time_left % 5 == 0 end - @logger.warn "" if @logger + @logger&.warn "" @app.call(original_env) else diff --git a/lib/zendesk_api/middleware/request/upload.rb b/lib/zendesk_api/middleware/request/upload.rb index 79fd2c0f..9d5bb53e 100644 --- a/lib/zendesk_api/middleware/request/upload.rb +++ b/lib/zendesk_api/middleware/request/upload.rb @@ -1,6 +1,6 @@ require "faraday/middleware" require "mini_mime" -require 'tempfile' +require "tempfile" module ZendeskAPI module Middleware diff --git a/lib/zendesk_api/middleware/request/url_based_access_token.rb b/lib/zendesk_api/middleware/request/url_based_access_token.rb index 82280b94..fb3664fd 100644 --- a/lib/zendesk_api/middleware/request/url_based_access_token.rb +++ b/lib/zendesk_api/middleware/request/url_based_access_token.rb @@ -11,9 +11,9 @@ def initialize(app, token) def call(env) if env[:url].query - env[:url].query += '&' + env[:url].query += "&" else - env[:url].query = '' + env[:url].query = "" end env[:url].query += "access_token=#{@token}" diff --git a/lib/zendesk_api/middleware/response/deflate.rb b/lib/zendesk_api/middleware/response/deflate.rb index dc8116b2..b2925fa3 100644 --- a/lib/zendesk_api/middleware/response/deflate.rb +++ b/lib/zendesk_api/middleware/response/deflate.rb @@ -7,7 +7,7 @@ module Response # @private class Deflate < Faraday::Middleware def on_complete(env) - return if env[:response_headers]['content-encoding'] != "deflate" + return if env[:response_headers]["content-encoding"] != "deflate" return if env.body.strip.empty? env.body = Zlib::Inflate.inflate(env.body) diff --git a/lib/zendesk_api/middleware/response/gzip.rb b/lib/zendesk_api/middleware/response/gzip.rb index 3d6e4259..a182261c 100644 --- a/lib/zendesk_api/middleware/response/gzip.rb +++ b/lib/zendesk_api/middleware/response/gzip.rb @@ -1,5 +1,5 @@ -require 'zlib' -require 'stringio' +require "zlib" +require "stringio" module ZendeskAPI # @private @@ -9,7 +9,7 @@ module Response # Faraday middleware to handle content-encoding = gzip class Gzip < Faraday::Middleware def on_complete(env) - return if env[:response_headers]['content-encoding'] != "gzip" + return if env[:response_headers]["content-encoding"] != "gzip" return if env[:body].force_encoding(Encoding::BINARY).strip.empty? env[:body] = Zlib::GzipReader.new(StringIO.new(env[:body])).read diff --git a/lib/zendesk_api/middleware/response/logger.rb b/lib/zendesk_api/middleware/response/logger.rb index d74ce80e..2c6ff801 100644 --- a/lib/zendesk_api/middleware/response/logger.rb +++ b/lib/zendesk_api/middleware/response/logger.rb @@ -10,13 +10,13 @@ def initialize(app, logger = nil) super(app) @logger = logger || begin - require 'logger' + require "logger" ::Logger.new($stdout) end end def call(env) - @logger.info "#{env[:method]} #{env[:url].to_s}" + @logger.info "#{env[:method]} #{env[:url]}" @logger.debug dump_debug(env, :request_headers) @app.call(env).on_complete do |env| diff --git a/lib/zendesk_api/middleware/response/parse_iso_dates.rb b/lib/zendesk_api/middleware/response/parse_iso_dates.rb index fe41f289..1cd11ee6 100644 --- a/lib/zendesk_api/middleware/response/parse_iso_dates.rb +++ b/lib/zendesk_api/middleware/response/parse_iso_dates.rb @@ -1,4 +1,4 @@ -require 'time' +require "time" require "faraday/response" module ZendeskAPI diff --git a/lib/zendesk_api/middleware/response/parse_json.rb b/lib/zendesk_api/middleware/response/parse_json.rb index aabbf008..2c3689a3 100644 --- a/lib/zendesk_api/middleware/response/parse_json.rb +++ b/lib/zendesk_api/middleware/response/parse_json.rb @@ -4,13 +4,13 @@ module Middleware # @private module Response class ParseJson < Faraday::Middleware - CONTENT_TYPE = 'Content-Type'.freeze + CONTENT_TYPE = "Content-Type".freeze def on_complete(env) type = env[:response_headers][CONTENT_TYPE].to_s - type = type.split(';', 2).first if type.index(';') + type = type.split(";", 2).first if type.index(";") - return unless type == 'application/json' + return unless type == "application/json" unless env[:body].strip.empty? env[:body] = JSON.parse(env[:body]) diff --git a/lib/zendesk_api/middleware/response/raise_error.rb b/lib/zendesk_api/middleware/response/raise_error.rb index 8b71234d..eebdc1ae 100644 --- a/lib/zendesk_api/middleware/response/raise_error.rb +++ b/lib/zendesk_api/middleware/response/raise_error.rb @@ -1,4 +1,4 @@ -require 'zendesk_api/error' +require_relative "../../error" module ZendeskAPI module Middleware diff --git a/lib/zendesk_api/middleware/response/sanitize_response.rb b/lib/zendesk_api/middleware/response/sanitize_response.rb index f3c03755..6b335411 100644 --- a/lib/zendesk_api/middleware/response/sanitize_response.rb +++ b/lib/zendesk_api/middleware/response/sanitize_response.rb @@ -3,7 +3,7 @@ module Middleware module Response class SanitizeResponse < Faraday::Middleware def on_complete(env) - env[:body].scrub!('') + env[:body].scrub!("") end end end diff --git a/lib/zendesk_api/pagination.rb b/lib/zendesk_api/pagination.rb index 06dd2150..796d751d 100644 --- a/lib/zendesk_api/pagination.rb +++ b/lib/zendesk_api/pagination.rb @@ -6,7 +6,7 @@ module Pagination def more_results?(response) Helpers.present?(response["meta"]) && response["meta"]["has_more"] end - alias has_more_results? more_results? # For backward compatibility with 1.33.0 and 1.34.0 + alias_method :has_more_results?, :more_results? # For backward compatibility with 1.33.0 and 1.34.0 # Changes the per_page option. Returns self, so it can be chained. No execution. # @return [Collection] self @@ -49,7 +49,7 @@ def cbp_response?(body) def set_cbp_options @options_per_page_was = @options.delete("per_page") # Default to CBP by using the page param as a map - @options.page = { size: @options_per_page_was || DEFAULT_PAGE_SIZE } + @options.page = {size: @options_per_page_was || DEFAULT_PAGE_SIZE} end # CBP requests look like: `/resources?page[size]=100` @@ -92,7 +92,7 @@ def set_cbp_response_options(body) @options.page.merge!( before: body["meta"]["before_cursor"], after: body["meta"]["after_cursor"] - ) + ) end end end diff --git a/lib/zendesk_api/resource.rb b/lib/zendesk_api/resource.rb index ffe526c3..3cf01ba9 100644 --- a/lib/zendesk_api/resource.rb +++ b/lib/zendesk_api/resource.rb @@ -1,9 +1,9 @@ -require 'zendesk_api/helpers' -require 'zendesk_api/trackie' -require 'zendesk_api/actions' -require 'zendesk_api/association' -require 'zendesk_api/associations' -require 'zendesk_api/verbs' +require_relative "helpers" +require_relative "trackie" +require_relative "actions" +require_relative "association" +require_relative "associations" +require_relative "verbs" # See docs: https://developer.zendesk.com/api-reference/ module ZendeskAPI @@ -34,7 +34,7 @@ def resource_path [@namespace, resource_name].compact.join("/") end - alias :model_key :resource_name + alias_method :model_key, :resource_name def namespace(namespace) @namespace = namespace @@ -64,7 +64,7 @@ def new_from_response(client, response, includes = nil) def initialize(client, attributes = {}) raise "Expected a Hash for attributes, got #{attributes.inspect}" unless attributes.is_a?(Hash) - @association = attributes.delete(:association) || Association.new(:class => self.class) + @association = attributes.delete(:association) || Association.new(class: self.class) @global_params = attributes.delete(:global) || {} @client = client @attributes = ZendeskAPI::Trackie.new(attributes) @@ -76,14 +76,6 @@ def initialize(client, attributes = {}) @attributes.clear_changes unless new_record? end - def self.new_from_response(client, response, includes = nil) - new(client).tap do |resource| - resource.handle_response(response) - resource.set_includes(resource, includes, response.body) if includes - resource.attributes.clear_changes - end - end - # Passes the method onto the attributes hash. # If the attributes are nested (e.g. { :tickets => { :id => 1 } }), passes the method onto the nested hash. def method_missing(*args, &) @@ -127,7 +119,6 @@ def to_json(*args) def to_s "#{self.class.singular_resource_name}: #{attributes.inspect}" end - alias :inspect :to_s # Compares resources by class and id. If id is nil, then by object_id def ==(other) @@ -140,19 +131,19 @@ def ==(other) return id == other if other.is_a?(Integer) warn "Trying to compare #{other.class} to a Resource - from #{caller.first}" + from #{caller(1..1).first}" end - alias :eql :== + alias_method :eql, :== # @private def inspect "#<#{self.class.name} #{@attributes.to_hash.inspect}>" end - alias :to_param :attributes + alias_method :to_param, :attributes def attributes_for_save - { self.class.singular_resource_name.to_sym => attribute_changes } + {self.class.singular_resource_name.to_sym => attribute_changes} end private @@ -206,7 +197,7 @@ class Resource < DataResource class SingularResource < Resource def attributes_for_save - { self.class.resource_name.to_sym => attribute_changes } + {self.class.resource_name.to_sym => attribute_changes} end end diff --git a/lib/zendesk_api/resources.rb b/lib/zendesk_api/resources.rb index 7df38c4e..ec55822d 100644 --- a/lib/zendesk_api/resources.rb +++ b/lib/zendesk_api/resources.rb @@ -20,7 +20,7 @@ class WorkItem < Resource; end class Channel < Resource def work_items - @work_items ||= attributes.fetch('relationships', {}).fetch('work_items', {}).fetch('data', []).map do |work_item_attributes| + @work_items ||= attributes.fetch("relationships", {}).fetch("work_items", {}).fetch("data", []).map do |work_item_attributes| WorkItem.new(@client, work_item_attributes) end end @@ -35,7 +35,7 @@ def self.model_key end def initialize(client, attributes = {}) - nested_attributes = attributes.delete('attributes') + nested_attributes = attributes.delete("attributes") super(client, attributes.merge(nested_attributes)) end @@ -59,9 +59,9 @@ def self.search(client, args_hash) def channels @channels ||= begin - channel_attributes_array = @client.connection.get(attributes['links']['self']).body.fetch('included') + channel_attributes_array = @client.connection.get(attributes["links"]["self"]).body.fetch("included") channel_attributes_array.map do |channel_attributes| - nested_attributes = channel_attributes.delete('attributes') + nested_attributes = channel_attributes.delete("attributes") Channel.new(@client, channel_attributes.merge(nested_attributes)) end end @@ -100,12 +100,12 @@ class Tag < DataResource include Update include Destroy - alias :name :id - alias :to_param :id + alias_method :name, :id + alias_method :to_param, :id def path(opts = {}) raise "tags must have parent resource" unless association.options.parent - super(opts.merge(:with_parent => true, :with_id => false)) + super(opts.merge(with_parent: true, with_id: false)) end def changed? @@ -123,7 +123,7 @@ def _save(method = :save) return self unless @resources @client.connection.post(path) do |req| - req.body = { :tags => @resources.reject(&:destroyed?).map(&:id) } + req.body = {tags: @resources.reject(&:destroyed?).map(&:id)} end true @@ -137,7 +137,7 @@ def _save(method = :save) end def attributes_for_save - { self.class.resource_name => [id] } + {self.class.resource_name => [id]} end def self.cbp_path_regexes @@ -195,13 +195,13 @@ class Organization < Resource extend CreateOrUpdate extend DestroyMany - has Ability, :inline => true + has Ability, inline: true has Group - has :related, :class => OrganizationRelated + has :related, class: OrganizationRelated has_many Ticket has_many User - has_many Tag, :extend => Tag::Update, :inline => :create + has_many Tag, extend: Tag::Update, inline: :create has_many OrganizationMembership has_many :subscriptions, class: OrganizationSubscription @@ -210,7 +210,7 @@ class Organization < Resource # @param [Integer] start_time The start_time parameter # @return [Collection] Collection of {Organization} def self.incremental_export(client, start_time) - ZendeskAPI::Collection.new(client, self, :path => "incremental/organizations?start_time=#{start_time.to_i}") + ZendeskAPI::Collection.new(client, self, path: "incremental/organizations?start_time=#{start_time.to_i}") end def self.cbp_path_regexes @@ -327,7 +327,7 @@ def model_key has User def path(options = {}) - super(options.merge(:with_parent => true)) + super(options.merge(with_parent: true)) end end @@ -340,7 +340,7 @@ class Topic < Resource class Activity < Resource has User - has :actor, :class => User + has :actor, class: User def self.cbp_path_regexes [/^activities$/] @@ -352,7 +352,7 @@ class Setting < UpdateResource def initialize(client, attributes = {}) # Try and find the root key - @on = (attributes.keys.map(&:to_s) - %w{association options}).first + @on = (attributes.keys.map(&:to_s) - %w[association options]).first # Make what's inside that key the root attributes attributes.merge!(attributes.delete(@on)) @@ -365,17 +365,17 @@ def new_record? end def path(options = {}) - super(options.merge(:with_parent => true)) + super(options.merge(with_parent: true)) end def attributes_for_save - { self.class.resource_name => { @on => attributes.changes } } + {self.class.resource_name => {@on => attributes.changes}} end end class SatisfactionRating < ReadResource - has :assignee, :class => User - has :requester, :class => User + has :assignee, class: User + has :requester, class: User has Ticket has Group end @@ -397,7 +397,7 @@ class Comment < DataResource include Save has_many :uploads, class: Attachment, inline: true - has :author, :class => User + has :author, class: User def save if new_record? @@ -408,23 +408,23 @@ def save end end - alias :save! :save + alias_method :save!, :save end - has Comment, :inline => true + has Comment, inline: true has_many Comment has Organization has Group - has :requester, :class => User + has :requester, class: User end class AnonymousRequest < CreateResource def self.singular_resource_name - 'request' + "request" end - namespace 'portal' + namespace "portal" end class TicketField < Resource @@ -448,14 +448,14 @@ class Event < Data; end has_many :child_events, class: Event has Ticket - has :updater, :class => User + has :updater, class: User # Gets a incremental export of ticket events from the start_time until now. # @param [Client] client The {Client} object to be used # @param [Integer] start_time The start_time parameter # @return [Collection] Collection of {TicketEvent} def self.incremental_export(client, start_time) - ZendeskAPI::Collection.new(client, self, :path => "incremental/ticket_events?start_time=#{start_time.to_i}") + ZendeskAPI::Collection.new(client, self, path: "incremental/ticket_events?start_time=#{start_time.to_i}") end end @@ -477,13 +477,13 @@ def attribute_changes class Audit < DataResource class Event < Data - has :author, :class => User + has :author, class: User end put :trust # need this to support SideLoading - has :author, :class => User + has :author, class: User has_many Event @@ -507,21 +507,21 @@ def save end end - alias :save! :save + alias_method :save!, :save end class SatisfactionRating < CreateResource class << self - alias :resource_name :singular_resource_name + alias_method :resource_name, :singular_resource_name end end put :mark_as_spam post :merge - has :requester, :class => User, :inline => :create - has :submitter, :class => User - has :assignee, :class => User + has :requester, class: User, inline: :create + has :submitter, class: User + has :assignee, class: User has_many :collaborators, class: User, inline: true, extend: Module.new do def to_param @@ -623,7 +623,7 @@ def self.model_key end class RuleExecution < Data - has_many :custom_fields, :class => TicketField + has_many :custom_fields, class: TicketField end class ViewCount < DataResource; end @@ -633,7 +633,7 @@ class Rule < Resource def attributes_for_save to_save = [:conditions, :actions, :output].inject({}) { |h, k| h.merge(k => send(k)) } - { self.class.singular_resource_name.to_sym => attributes.changes.merge(to_save) } + {self.class.singular_resource_name.to_sym => attributes.changes.merge(to_save)} end end @@ -653,32 +653,32 @@ def any_conditions=(any_conditions) def add_all_condition(field, operator, value) self.conditions ||= {} self.conditions[:all] ||= [] - self.conditions[:all] << { :field => field, :operator => operator, :value => value } + self.conditions[:all] << {field: field, operator: operator, value: value} end def add_any_condition(field, operator, value) self.conditions ||= {} self.conditions[:any] ||= [] - self.conditions[:any] << { :field => field, :operator => operator, :value => value } + self.conditions[:any] << {field: field, operator: operator, value: value} end end module Actions def add_action(field, value) self.actions ||= [] - self.actions << { :field => field, :value => value } + self.actions << {field: field, value: value} end end class View < Rule include Conditions - has_many :tickets, :class => Ticket - has_many :feed, :class => Ticket, :path => "feed" + has_many :tickets, class: Ticket + has_many :feed, class: Ticket, path: "feed" - has_many :rows, :class => ViewRow, :path => "execute" - has :execution, :class => RuleExecution - has ViewCount, :path => "count" + has_many :rows, class: ViewRow, path: "execute" + has :execution, class: RuleExecution + has ViewCount, path: "count" def add_column(column) columns = execution.columns.map(&:id) @@ -692,7 +692,7 @@ def columns=(columns) end def self.preview(client, options = {}) - Collection.new(client, ViewRow, options.merge(:path => "views/preview", :verb => :post)) + Collection.new(client, ViewRow, options.merge(path: "views/preview", verb: :post)) end def self.cbp_path_regexes @@ -704,7 +704,7 @@ class Trigger < Rule include Conditions include Actions - has :execution, :class => RuleExecution + has :execution, class: RuleExecution def self.cbp_path_regexes [/^triggers$/, %r{^triggers/active$}] @@ -715,7 +715,7 @@ class Automation < Rule include Conditions include Actions - has :execution, :class => RuleExecution + has :execution, class: RuleExecution def self.cbp_path_regexes [/^automations$/] @@ -725,7 +725,7 @@ def self.cbp_path_regexes class Macro < Rule include Actions - has :execution, :class => RuleExecution + has :execution, class: RuleExecution def self.cbp_path_regexes [/^macros$/] @@ -756,7 +756,7 @@ def apply(ticket = nil) class UserView < Rule def self.preview(client, options = {}) - Collection.new(client, UserViewRow, options.merge!(:path => "user_views/preview", :verb => :post)) + Collection.new(client, UserViewRow, options.merge!(path: "user_views/preview", verb: :post)) end end @@ -810,22 +810,22 @@ def self.cbp_path_regexes # Set a user's password def set_password(opts = {}) - password(opts.merge(:verb => :post)) + password(opts.merge(verb: :post)) end # Change a user's password def change_password(opts = {}) - password(opts.merge(:verb => :put)) + password(opts.merge(verb: :put)) end # Set a user's password def set_password!(opts = {}) - password!(opts.merge(:verb => :post)) + password!(opts.merge(verb: :post)) end # Change a user's password def change_password!(opts = {}) - password!(opts.merge(:verb => :put)) + password!(opts.merge(verb: :put)) end # Gets a incremental export of users from the start_time until now. @@ -833,7 +833,7 @@ def change_password!(opts = {}) # @param [Integer] start_time The start_time parameter # @return [Collection] Collection of {User} def self.incremental_export(client, start_time) - ZendeskAPI::Collection.new(client, self, :path => "incremental/users?start_time=#{start_time.to_i}") + ZendeskAPI::Collection.new(client, self, path: "incremental/users?start_time=#{start_time.to_i}") end has Organization @@ -844,17 +844,17 @@ class Session < Resource class CurrentSession < SingularResource class << self def singular_resource_name - 'session' + "session" end - alias :resource_name :singular_resource_name + alias_method :resource_name, :singular_resource_name end end has_many Session def current_session - ZendeskAPI::User::CurrentSession.find(@client, :user_id => 'me') + ZendeskAPI::User::CurrentSession.find(@client, user_id: "me") end delete :logout @@ -871,17 +871,17 @@ def clear_sessions put :merge - has CustomRole, :inline => true, :include => :roles - has Role, :inline => true, :include_key => :name - has Ability, :inline => true - has :related, :class => UserRelated + has CustomRole, inline: true, include: :roles + has Role, inline: true, include_key: :name + has Ability, inline: true + has :related, class: UserRelated has_many Identity has_many Request - has_many :requested_tickets, :class => Ticket, :path => 'tickets/requested' - has_many :assigned_tickets, :class => Ticket, :path => 'tickets/assigned' - has_many :ccd_tickets, :class => Ticket, :path => 'tickets/ccd' + has_many :requested_tickets, class: Ticket, path: "tickets/requested" + has_many :assigned_tickets, class: Ticket, path: "tickets/assigned" + has_many :ccd_tickets, class: Ticket, path: "tickets/ccd" has_many Group has_many GroupMembership @@ -889,7 +889,7 @@ def clear_sessions has_many OrganizationSubscription has_many Setting - has_many Tag, :extend => Tag::Update, :inline => :create + has_many Tag, extend: Tag::Update, inline: :create def attributes_for_save # Don't send role_id, it's necessary @@ -899,7 +899,7 @@ def attributes_for_save k == "role_id" end - { self.class.singular_resource_name => attrs } + {self.class.singular_resource_name => attrs} end def handle_response(*) @@ -1036,8 +1036,8 @@ def initialize(client, attributes = {}) end def self.create!(client, attributes = {}, &) - if file_path = attributes.delete(:upload) - attributes[:upload_id] = client.apps.uploads.create!(:file => file_path).id + if (file_path = attributes.delete(:upload)) + attributes[:upload_id] = client.apps.uploads.create!(file: file_path).id end super @@ -1087,7 +1087,7 @@ def self.installations(client, ...) ZendeskAPI::Collection.new(client, AppInstallation, ...) end - has Upload, :path => "uploads" + has Upload, path: "uploads" has_many Plan # Don't nest attributes @@ -1104,7 +1104,7 @@ module DynamicContent include DataNamespace class Item < ZendeskAPI::Resource - namespace 'dynamic_content' + namespace "dynamic_content" class Variant < ZendeskAPI::Resource end diff --git a/lib/zendesk_api/search.rb b/lib/zendesk_api/search.rb index e7707e67..d838cec4 100644 --- a/lib/zendesk_api/search.rb +++ b/lib/zendesk_api/search.rb @@ -35,7 +35,7 @@ class << self def resource_name "search" end - alias resource_path resource_name + alias_method :resource_path, :resource_name def model_key "results" @@ -49,7 +49,7 @@ class << self def resource_name "search/export" end - alias resource_path resource_name + alias_method :resource_path, :resource_name end end end diff --git a/lib/zendesk_api/silent_mash.rb b/lib/zendesk_api/silent_mash.rb index 2d463a69..534a362f 100644 --- a/lib/zendesk_api/silent_mash.rb +++ b/lib/zendesk_api/silent_mash.rb @@ -1,4 +1,4 @@ -require 'hashie' +require "hashie" module ZendeskAPI # @private diff --git a/lib/zendesk_api/track_changes.rb b/lib/zendesk_api/track_changes.rb index df8dd427..afb8010e 100644 --- a/lib/zendesk_api/track_changes.rb +++ b/lib/zendesk_api/track_changes.rb @@ -79,7 +79,7 @@ def changed?(key = nil) end end - alias :dirty? :changed? + alias_method :dirty?, :changed? end end end diff --git a/lib/zendesk_api/trackie.rb b/lib/zendesk_api/trackie.rb index 59f1fc49..c263cd34 100644 --- a/lib/zendesk_api/trackie.rb +++ b/lib/zendesk_api/trackie.rb @@ -1,5 +1,5 @@ -require 'zendesk_api/track_changes' -require 'zendesk_api/silent_mash' +require_relative "track_changes" +require_relative "silent_mash" module ZendeskAPI # @private @@ -7,7 +7,7 @@ class Trackie < SilentMash include ZendeskAPI::TrackChanges def size - self['size'] + self["size"] end end end diff --git a/spec/core/association_spec.rb b/spec/core/association_spec.rb index 02520ce1..4d2a80bc 100644 --- a/spec/core/association_spec.rb +++ b/spec/core/association_spec.rb @@ -1,14 +1,12 @@ -require 'core/spec_helper' - describe ZendeskAPI::Association do - let(:instance) { ZendeskAPI::TestResource.new(client, :id => 1) } - let(:child) { ZendeskAPI::TestResource::TestChild.new(client, :id => 1, :test_resource_id => 2) } + let(:instance) { ZendeskAPI::TestResource.new(client, id: 1) } + let(:child) { ZendeskAPI::TestResource::TestChild.new(client, id: 1, test_resource_id: 2) } describe "setting/getting" do context "has" do before do ZendeskAPI::TestResource.associations.clear - ZendeskAPI::TestResource.has :child, :class => ZendeskAPI::TestResource::TestChild + ZendeskAPI::TestResource.has :child, class: ZendeskAPI::TestResource::TestChild end it "should not try and fetch nil child" do @@ -28,7 +26,7 @@ end it "should build a object set via hash" do - instance.child = { :id => 2 } + instance.child = {id: 2} expect(instance.child.id).to eq(2) end @@ -42,19 +40,19 @@ end it "should fetch an object known by id" do - stub_json_request(:get, %r{test_resources/1/child/5}, json(:test_child => { :id => 5 })) + stub_json_request(:get, %r{test_resources/1/child/5}, json(test_child: {id: 5})) instance.child_id = 5 expect(instance.child.id).to eq(5) end it "should handle client errors" do - stub_request(:get, %r{test_resources/1/child/5}).to_return(:status => 500) + stub_request(:get, %r{test_resources/1/child/5}).to_return(status: 500) instance.child_id = 5 expect { silence_logger { instance.child } }.to_not raise_error end it "should handle resource not found errors" do - stub_request(:get, %r{test_resources/1/child/5}).to_return(:status => 404) + stub_request(:get, %r{test_resources/1/child/5}).to_return(status: 404) instance.child_id = 5 silence_logger { expect(instance.child).to be_nil } end @@ -84,7 +82,7 @@ end it "should build and cache objects set via hash" do - instance.children = [{ :id => 2 }] + instance.children = [{id: 2}] expect(instance.children.map(&:id)).to eq([2]) expect(instance.children).to be_instance_of(ZendeskAPI::Collection) end @@ -96,16 +94,16 @@ end it "should fetch unknown objects" do - stub_json_request(:get, %r{test_resources/1/children}, json(:test_children => [{ :id => 2 }, { :id => 3 }])) + stub_json_request(:get, %r{test_resources/1/children}, json(test_children: [{id: 2}, {id: 3}])) expect(instance.children.map(&:id)).to eq([2, 3]) expect(instance.children).to be_instance_of(ZendeskAPI::Collection) end it "should not change objects" do - child = 'foo' + child = "foo" children = [child] instance.children = children - expect(children[0]).to eq('foo') + expect(children[0]).to eq("foo") end it "is not used when not used" do @@ -120,7 +118,7 @@ end context "class only" do - subject { described_class.new(:class => ZendeskAPI::TestResource) } + subject { described_class.new(class: ZendeskAPI::TestResource) } it "should generate resource path" do expect(subject.generate_path).to eq("test_resources") @@ -133,7 +131,7 @@ context "with_id => false" do it "should generate general resource path" do - expect(subject.generate_path(instance, :with_id => false)).to eq("test_resources") + expect(subject.generate_path(instance, with_id: false)).to eq("test_resources") end end @@ -154,7 +152,7 @@ context "with a passed in id" do it "should generate specific resource path" do - opts = { :id => 1 } + opts = {id: 1} expect(subject.generate_path(opts)).to eq("test_resources/1") expect(opts).to be_empty end @@ -162,7 +160,7 @@ end context "class with a specified parent" do - subject { described_class.new(:class => ZendeskAPI::TestResource::TestChild, :parent => instance, :name => :children) } + subject { described_class.new(class: ZendeskAPI::TestResource::TestChild, parent: instance, name: :children) } it "should generate nested resource path" do expect(subject.generate_path).to eq("test_resources/1/children") @@ -175,14 +173,14 @@ context "with_id => false" do it "should generate nested resource path" do - expect(subject.generate_path(child, :with_id => false)).to eq("test_resources/1/children") + expect(subject.generate_path(child, with_id: false)).to eq("test_resources/1/children") end end end context "when parent has a namespace" do before(:each) do - instance.class.namespace 'hello' + instance.class.namespace "hello" end after(:each) do @@ -225,7 +223,7 @@ end context "class with a parent id" do - subject { described_class.new(:class => ZendeskAPI::TestResource::TestChild, :name => :children) } + subject { described_class.new(class: ZendeskAPI::TestResource::TestChild, name: :children) } it "should raise an error if not passed an instance or id" do expect { subject.generate_path }.to raise_error(ArgumentError) @@ -237,7 +235,7 @@ context "with parent id passed in" do it "should generate nested resource path" do - opts = { :test_resource_id => 3 } + opts = {test_resource_id: 3} expect(subject.generate_path(opts)).to eq("test_resources/3/children") expect(opts).to be_empty end @@ -245,11 +243,11 @@ end context "with a singular resource" do - subject { described_class.new(:class => ZendeskAPI::SingularTestResource) } + subject { described_class.new(class: ZendeskAPI::SingularTestResource) } context "with an instance" do it "should not generate a specific resource path" do - expect(subject.generate_path(ZendeskAPI::SingularTestResource.new(client, :id => 1))).to eq("singular_test_resources") + expect(subject.generate_path(ZendeskAPI::SingularTestResource.new(client, id: 1))).to eq("singular_test_resources") end end end diff --git a/spec/core/bulk_actions_spec.rb b/spec/core/bulk_actions_spec.rb index ed3e0212..0f187604 100644 --- a/spec/core/bulk_actions_spec.rb +++ b/spec/core/bulk_actions_spec.rb @@ -1,21 +1,19 @@ -require 'core/spec_helper' - describe ZendeskAPI::DestroyMany do subject { ZendeskAPI::BulkTestResource } context "destroy_many!" do before(:each) do - stub_json_request(:delete, %r{bulk_test_resources/destroy_many}, json(:job_status => { :id => 'abc' })) + stub_json_request(:delete, %r{bulk_test_resources/destroy_many}, json(job_status: {id: "abc"})) @response = subject.destroy_many!(client, [1, 2, 3]) end - it 'calls the destroy_many endpoint' do + it "calls the destroy_many endpoint" do assert_requested(:delete, %r{bulk_test_resources/destroy_many\?ids=1,2,3$}) end - it 'returns a JobStatus' do + it "returns a JobStatus" do expect(@response).to be_instance_of(ZendeskAPI::JobStatus) - expect(@response.id).to eq('abc') + expect(@response.id).to eq("abc") end end end @@ -24,22 +22,21 @@ subject { ZendeskAPI::BulkTestResource } context "create_many!" do - let(:attributes) { [{ :name => 'A' }, { :name => 'B' }] } + let(:attributes) { [{name: "A"}, {name: "B"}] } before(:each) do - stub_json_request(:post, %r{bulk_test_resources/create_many}, json(:job_status => { :id => 'def' })) + stub_json_request(:post, %r{bulk_test_resources/create_many}, json(job_status: {id: "def"})) @response = subject.create_many!(client, attributes) end - it 'calls the create_many endpoint' do + it "calls the create_many endpoint" do assert_requested(:post, %r{bulk_test_resources/create_many}, - :body => json(:bulk_test_resources => attributes) - ) + body: json(bulk_test_resources: attributes)) end - it 'returns a JobStatus' do + it "returns a JobStatus" do expect(@response).to be_instance_of(ZendeskAPI::JobStatus) - expect(@response.id).to eq('def') + expect(@response.id).to eq("def") end end @@ -48,42 +45,40 @@ context "update_many!" do context "updating a list of ids" do - let(:attributes) { { :name => 'A', :age => 25 } } + let(:attributes) { {name: "A", age: 25} } before(:each) do - stub_json_request(:put, %r{bulk_test_resources/update_many}, json(:job_status => { :id => 'ghi' })) + stub_json_request(:put, %r{bulk_test_resources/update_many}, json(job_status: {id: "ghi"})) @response = subject.update_many!(client, [1, 2, 3], attributes) end - it 'calls the update_many endpoint' do + it "calls the update_many endpoint" do assert_requested(:put, %r{bulk_test_resources/update_many\?ids=1,2,3$}, - :body => json(:bulk_test_resource => attributes) - ) + body: json(bulk_test_resource: attributes)) end - it 'returns a JobStatus' do + it "returns a JobStatus" do expect(@response).to be_instance_of(ZendeskAPI::JobStatus) - expect(@response.id).to eq('ghi') + expect(@response.id).to eq("ghi") end end context "updating with multiple attribute hashes" do - let(:attributes) { [{ :id => 1, :name => 'A' }, { :id => 2, :name => 'B' }] } + let(:attributes) { [{id: 1, name: "A"}, {id: 2, name: "B"}] } before(:each) do - stub_json_request(:put, %r{bulk_test_resources/update_many}, json(:job_status => { :id => 'jkl' })) + stub_json_request(:put, %r{bulk_test_resources/update_many}, json(job_status: {id: "jkl"})) @response = subject.update_many!(client, attributes) end - it 'calls the update_many endpoint' do + it "calls the update_many endpoint" do assert_requested(:put, %r{bulk_test_resources/update_many$}, - :body => json(:bulk_test_resources => attributes) - ) + body: json(bulk_test_resources: attributes)) end - it 'returns a JobStatus' do + it "returns a JobStatus" do expect(@response).to be_instance_of(ZendeskAPI::JobStatus) - expect(@response.id).to eq('jkl') + expect(@response.id).to eq("jkl") end end end @@ -95,25 +90,24 @@ context "create_or_update_many!" do context "creating or updating with multiple attribute hashes" do - let(:attributes) { [{ :id => 1, :name => 'A' }, { :id => 2, :name => 'B' }] } + let(:attributes) { [{id: 1, name: "A"}, {id: 2, name: "B"}] } subject { resource.create_or_update_many!(client, attributes) } before do - stub_json_request(:post, %r{bulk_test_resources/create_or_update_many}, json(:job_status => { :id => 'jkl' })) + stub_json_request(:post, %r{bulk_test_resources/create_or_update_many}, json(job_status: {id: "jkl"})) end - it 'calls the create_or_update_many endpoint' do + it "calls the create_or_update_many endpoint" do subject assert_requested(:post, %r{bulk_test_resources/create_or_update_many$}, - :body => json(:bulk_test_resources => attributes) - ) + body: json(bulk_test_resources: attributes)) end - it 'returns a JobStatus' do + it "returns a JobStatus" do expect(subject).to be_a(ZendeskAPI::JobStatus) - expect(subject.id).to eq('jkl') + expect(subject.id).to eq("jkl") end end end diff --git a/spec/core/client_spec.rb b/spec/core/client_spec.rb index 46cbbd38..570d4a17 100644 --- a/spec/core/client_spec.rb +++ b/spec/core/client_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - class SimpleClient < ZendeskAPI::Client def build_connection "FOO" @@ -17,7 +15,7 @@ def build_connection config.adapter = :test config.adapter_proc = proc do |stub| stub.get "/api/v2/tickets" do |_env| - [200, { 'Content-Type': "application/json" }, "null"] + [200, {"Content-Type": "application/json"}, "null"] end end end @@ -124,7 +122,7 @@ def url.to_str config.url = "https://example.zendesk.com/api/v2" config.username = username config.token = "token" - config.client_options = { :request => { :timeout => 30 } } + config.client_options = {request: {timeout: 30}} end end @@ -176,7 +174,7 @@ def url.to_str config.logger = subject end - stub_request(:get, %r{/bs$}).to_return(:status => 200) + stub_request(:get, %r{/bs$}).to_return(status: 200) end context "with true value" do @@ -189,7 +187,7 @@ def url.to_str context "with a request" do it "should log" do expect(client.config.logger).to receive(:info).at_least(:once) - @client.connection.get('/bs') + @client.connection.get("/bs") end end end @@ -221,7 +219,7 @@ def url.to_str context "with a request" do it "should log to the subject" do expect(out).to receive(:write).at_least(:once) - @client.connection.get('/bs') + @client.connection.get("/bs") end end end @@ -263,20 +261,20 @@ def url.to_str end it "should not cache calls with different options" do - expect(subject.search(:query => 'abc')).to_not eq(subject.search(:query => '123')) + expect(subject.search(query: "abc")).to_not eq(subject.search(query: "123")) end it "should not cache calls with :reload => true options" do - expect(subject.search(:query => 'abc')).to_not eq(subject.search(:query => 'abc', :reload => true)) + expect(subject.search(query: "abc")).to_not eq(subject.search(query: "abc", reload: true)) end it "should not pass reload to the underlying collection" do - collection = subject.search(:query => 'abc', :reload => true) + collection = subject.search(query: "abc", reload: true) expect(collection.options.key?(:reload)).to be(false) end it "should cache calls with the same options" do - expect(subject.search(:query => 'abc')).to eq(subject.search(:query => 'abc')) + expect(subject.search(query: "abc")).to eq(subject.search(query: "abc")) end it "should respond_to? for valid resources" do @@ -304,10 +302,10 @@ def url.to_str end it "looks in the appropriate namespaces" do - expect(subject.greetings.association.options['class']).to eq(ZendeskAPI::Voice::Greeting) + expect(subject.greetings.association.options["class"]).to eq(ZendeskAPI::Voice::Greeting) end - it 'raises if the resource does not exist' do + it "raises if the resource does not exist" do expect { subject.random_resource }.to raise_error(RuntimeError) end @@ -320,7 +318,7 @@ def url.to_str end before(:each) do - stub_request(:get, %r{/bs$}).to_return(:status => 200) + stub_request(:get, %r{/bs$}).to_return(status: 200) end it "returns an instance of ZendeskAPI::Collection" do @@ -372,7 +370,7 @@ def url.to_str config.adapter = :test config.adapter_proc = proc do |stub| stub.get "/api/v2/tickets" do |env| - [200, { 'content-type': "application/json", Authorization: env.request_headers["Authorization"] }, "null"] + [200, {"content-type": "application/json", Authorization: env.request_headers["Authorization"]}, "null"] end end end diff --git a/spec/core/collection_spec.rb b/spec/core/collection_spec.rb index 6d9fffa7..150b035a 100644 --- a/spec/core/collection_spec.rb +++ b/spec/core/collection_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - describe ZendeskAPI::Collection do subject do ZendeskAPI::Collection.new(client, ZendeskAPI::TestResource) @@ -19,7 +17,7 @@ "prev" => nil, "next" => "https://zen.com/test_resources.json?page[after]=#{page2_cursor}&page[size]=2" }, - "test_resources" => [{ "id" => 1 }, { "id" => 2 }] + "test_resources" => [{"id" => 1}, {"id" => 2}] } end @@ -49,7 +47,7 @@ end context "with array option passed in" do - subject { ZendeskAPI::Collection.new(client, ZendeskAPI::TestResource, :ids => [1, 2, 3, 4]) } + subject { ZendeskAPI::Collection.new(client, ZendeskAPI::TestResource, ids: [1, 2, 3, 4]) } it "should join array with commas" do expect(subject.instance_variable_get(:@options)[:ids]).to eq("1,2,3,4") @@ -59,32 +57,31 @@ context "deferral" do it "should defer #create_many! to the resource class" do collection = ZendeskAPI::Collection.new(client, ZendeskAPI::BulkTestResource) - stub_json_request(:post, %r{bulk_test_resources/create_many$}, json(:job_status => {})) - collection.create_many!([{ :name => 'Mick' }, { :name => 'Steven' }]) + stub_json_request(:post, %r{bulk_test_resources/create_many$}, json(job_status: {})) + collection.create_many!([{name: "Mick"}, {name: "Steven"}]) assert_requested(:post, %r{bulk_test_resources/create_many$}, - :body => { - :bulk_test_resources => [{ :name => 'Mick' }, { :name => 'Steven' }] - } - ) + body: { + bulk_test_resources: [{name: "Mick"}, {name: "Steven"}] + }) end it "should defer #destroy_many! to the resource class" do collection = ZendeskAPI::Collection.new(client, ZendeskAPI::BulkTestResource) - stub_json_request(:delete, %r{bulk_test_resources/destroy_many\?}, json(:job_status => {})) + stub_json_request(:delete, %r{bulk_test_resources/destroy_many\?}, json(job_status: {})) collection.destroy_many!([1, 2, 3]) assert_requested(:delete, %r{bulk_test_resources/destroy_many\?ids=1,2,3$}) end it "should defer #update_many! to the resource class" do collection = ZendeskAPI::Collection.new(client, ZendeskAPI::BulkTestResource) - stub_json_request(:put, %r{bulk_test_resources/update_many\?}, json(:job_status => {})) - collection.update_many!([1, 2, 3], { :name => 'Mick' }) + stub_json_request(:put, %r{bulk_test_resources/update_many\?}, json(job_status: {})) + collection.update_many!([1, 2, 3], {name: "Mick"}) assert_requested(:put, %r{bulk_test_resources/update_many\?ids=1,2,3$}) end it "should defer #create_or_update to the resource class" do resource = ZendeskAPI::Collection.new(client, ZendeskAPI::CreateOrUpdateTestResource) - stub_json_request(:post, %r{create_or_update_test_resources/create_or_update}, json(create_or_update_test_resource: { param: "abc" })) + stub_json_request(:post, %r{create_or_update_test_resources/create_or_update}, json(create_or_update_test_resource: {param: "abc"})) resource.create_or_update! @@ -92,23 +89,23 @@ end it "should defer #create to the resource class" do - stub_json_request(:post, %r{test_resources$}, json(:test_resource => {})) + stub_json_request(:post, %r{test_resources$}, json(test_resource: {})) subject.create end it "should defer #find to the resource class" do - stub_json_request(:get, %r{test_resources/1$}, json(:test_resource => {})) - subject.find(:id => 1) + stub_json_request(:get, %r{test_resources/1$}, json(test_resource: {})) + subject.find(id: 1) end it "should defer #destroy to the resource class" do - stub_json_request(:delete, %r{test_resources/1$}, json(:test_resource => {})) - subject.destroy(:id => 1) + stub_json_request(:delete, %r{test_resources/1$}, json(test_resource: {})) + subject.destroy(id: 1) end it "should defer #update to the resource class" do - stub_json_request(:put, %r{test_resources/1$}, json(:test_resource => {})) - subject.update(:id => 1) + stub_json_request(:put, %r{test_resources/1$}, json(test_resource: {})) + subject.update(id: 1) end context "when class doesn't have method" do @@ -127,13 +124,13 @@ context "with a class with a parent" do let(:association) do - ZendeskAPI::Association.new(:class => ZendeskAPI::TestResource::TestChild, - :parent => ZendeskAPI::TestResource.new(client, :id => 1), :name => :children) + ZendeskAPI::Association.new(class: ZendeskAPI::TestResource::TestChild, + parent: ZendeskAPI::TestResource.new(client, id: 1), name: :children) end subject do ZendeskAPI::Collection.new(client, ZendeskAPI::TestResource::TestChild, - :association => association) + association: association) end before(:each) do @@ -145,21 +142,21 @@ end it "should defer #destroy the resource class with the parent id" do - subject.destroy(:id => 1) + subject.destroy(id: 1) end it "should defer #find to the resource class with the parent id" do - subject.find(:id => 1) + subject.find(id: 1) end it "should defer #update to the resource class with the parent id" do - subject.update(:id => 1) + subject.update(id: 1) end context "on object push" do before(:each) do - stub_json_request(:get, %r{test_resources/\d+/children}, json(:test_children => [])) - subject << { :id => 1 } + stub_json_request(:get, %r{test_resources/\d+/children}, json(test_children: [])) + subject << {id: 1} end it "should pass association" do @@ -184,8 +181,8 @@ context "pagination with data" do before(:each) do stub_json_request(:get, %r{test_resources}, json( - :test_resources => [{ :id => 1 }] - )) + test_resources: [{id: 1}] + )) subject.fetch(true) end @@ -262,19 +259,20 @@ context "Faraday errors" do before(:each) do stub_json_request(:get, %r{test_resources$}, json( - :test_resources => [{ :id => 1 }], :next_page => "/test_resources?page=2" + test_resources: [{id: 1}], next_page: "/test_resources?page=2" )) stub_request(:get, %r{test_resources\?page%5Bsize%5D=100}).to_raise(ZendeskAPI::Error::NetworkError) - stub_request(:get, %r{test_resources\?page=2}).to_return(:status => 500).then.to_return( - :headers => { :content_type => "application/json" }, :status => 200, - :body => json(:test_resources => [{ :id => 2 }], :next_page => "/test_resources?page=3")) + stub_request(:get, %r{test_resources\?page=2}).to_return(status: 500).then.to_return( + headers: {content_type: "application/json"}, status: 200, + body: json(test_resources: [{id: 2}], next_page: "/test_resources?page=3") + ) - stub_request(:get, %r{test_resources\?page=3}).to_return(:status => 404) + stub_request(:get, %r{test_resources\?page=3}).to_return(status: 404) end it "should retry from the same page" do - class SearchError < Exception; end + class SearchError < RuntimeError; end expect do |b| client.insert_callback do |env| @@ -289,8 +287,8 @@ class SearchError < Exception; end retry end end.to yield_successive_args( - [ZendeskAPI::TestResource.new(client, :id => 1), 1], - [ZendeskAPI::TestResource.new(client, :id => 2), 2] + [ZendeskAPI::TestResource.new(client, id: 1), 1], + [ZendeskAPI::TestResource.new(client, id: 2), 2] ) end @@ -301,8 +299,8 @@ class SearchError < Exception; end retry rescue ZendeskAPI::Error::ClientError end.to yield_successive_args( - [ZendeskAPI::TestResource.new(client, :id => 1), 1], - [ZendeskAPI::TestResource.new(client, :id => 2), 2] + [ZendeskAPI::TestResource.new(client, id: 1), 1], + [ZendeskAPI::TestResource.new(client, id: 2), 2] ) end @@ -322,13 +320,13 @@ class SearchError < Exception; end context "requests with no next_page" do before(:each) do stub_json_request(:get, %r{test_resources$}, json( - :test_resources => [{ :id => 1 }], - :next_page => "/test_resources?page=2" + test_resources: [{id: 1}], + next_page: "/test_resources?page=2" )) stub_json_request(:get, %r{test_resources\?page=2}, json( - :test_resources => [{ :id => 2 }] - )) + test_resources: [{id: 2}] + )) stub_request(:get, %r{test_resources\?page%5Bsize%5D=100}).to_raise(ZendeskAPI::Error::NetworkError) end @@ -336,26 +334,26 @@ class SearchError < Exception; end expect do |b| silence_logger { subject.all(&b) } end.to yield_successive_args( - [ZendeskAPI::TestResource.new(client, :id => 1), 1], - [ZendeskAPI::TestResource.new(client, :id => 2), 2] + [ZendeskAPI::TestResource.new(client, id: 1), 1], + [ZendeskAPI::TestResource.new(client, id: 2), 2] ) end end context "incremental requests" do subject do - ZendeskAPI::Collection.new(client, ZendeskAPI::TestResource, :path => 'incremental/test_resources?start_time=0') + ZendeskAPI::Collection.new(client, ZendeskAPI::TestResource, path: "incremental/test_resources?start_time=0") end before(:each) do stub_json_request(:get, %r{incremental/test_resources\?start_time=0$}, json( - :test_resources => [{ :id => 1 }], - :next_page => "/incremental/test_resources?start_time=200" + test_resources: [{id: 1}], + next_page: "/incremental/test_resources?start_time=200" )) stub_json_request(:get, %r{incremental/test_resources\?start_time=200$}, json( - :test_resources => [{ :id => 2 }], - :next_page => "/incremental/test_resources?start_time=200" + test_resources: [{id: 2}], + next_page: "/incremental/test_resources?start_time=200" )) stub_request(:get, %r{incremental/test_resources\?page%5Bsize%5D=100&start_time=0}).to_raise(ZendeskAPI::Error::NetworkError) @@ -368,8 +366,8 @@ class SearchError < Exception; end silence_logger { subject.all(&b) } end end.to yield_successive_args( - [ZendeskAPI::TestResource.new(client, :id => 1), 1], - [ZendeskAPI::TestResource.new(client, :id => 2), 1] # page defaults to 1 + [ZendeskAPI::TestResource.new(client, id: 1), 1], + [ZendeskAPI::TestResource.new(client, id: 2), 1] # page defaults to 1 ) end end @@ -377,13 +375,13 @@ class SearchError < Exception; end context "infinite loops" do before(:each) do stub_json_request(:get, %r{test_resources$}, json( - :test_resources => [{ :id => 1 }], - :next_page => "/test_resources?page=2" + test_resources: [{id: 1}], + next_page: "/test_resources?page=2" )) stub_json_request(:get, %r{/test_resources\?page=2$}, json( - :test_resources => [{ :id => 2 }], - :next_page => "/test_resources?page=2" + test_resources: [{id: 2}], + next_page: "/test_resources?page=2" )) end end @@ -391,21 +389,21 @@ class SearchError < Exception; end context "successful requests" do before(:each) do stub_json_request(:get, %r{test_resources$}, json( - :test_resources => [{ :id => 1 }], - :next_page => "/test_resources?page=2" + test_resources: [{id: 1}], + next_page: "/test_resources?page=2" )) stub_json_request(:get, %r{test_resources\?page%5Bsize%5D=100}, json( - :test_resources => [{ :id => 1 }], - :next_page => "/test_resources?page=2" + test_resources: [{id: 1}], + next_page: "/test_resources?page=2" )) stub_json_request(:get, %r{test_resources\?page=2}, json( - :test_resources => [{ :id => 2 }], - :next_page => "/test_resources?page=3" + test_resources: [{id: 2}], + next_page: "/test_resources?page=3" )) - stub_request(:get, %r{test_resources\?page=3}).to_return(:status => 404) + stub_request(:get, %r{test_resources\?page=3}).to_return(status: 404) end it "should yield resource if arity == 1" do @@ -417,7 +415,7 @@ def to_proc probe = self callback = @callback - Proc.new do |arg| + proc do |arg| probe.num_yields += 1 probe.yielded_args << [arg] callback.call([arg]) @@ -428,8 +426,8 @@ def to_proc silence_logger { subject.all(&block) } end.to yield_successive_args( - [ZendeskAPI::TestResource.new(client, :id => 1)], - [ZendeskAPI::TestResource.new(client, :id => 2)] + [ZendeskAPI::TestResource.new(client, id: 1)], + [ZendeskAPI::TestResource.new(client, id: 2)] ) end @@ -437,8 +435,8 @@ def to_proc expect do |b| silence_logger { subject.all(&b) } end.to yield_successive_args( - [ZendeskAPI::TestResource.new(client, :id => 1), 1], - [ZendeskAPI::TestResource.new(client, :id => 2), 2] + [ZendeskAPI::TestResource.new(client, id: 1), 1], + [ZendeskAPI::TestResource.new(client, id: 2), 2] ) end @@ -449,7 +447,7 @@ def to_proc it "should reset the collection" do expect(subject.first_page?).to be(true) - expect(subject.fetch).to eq([ZendeskAPI::TestResource.new(client, :id => 1)]) + expect(subject.fetch).to eq([ZendeskAPI::TestResource.new(client, id: 1)]) end end end @@ -460,8 +458,8 @@ def to_proc context "from next_page" do before(:each) do stub_json_request(:get, %r{test_resources}, json( - :test_resources => [{ :id => 2 }], - :next_page => "/test_resources?page=2" + test_resources: [{id: 2}], + next_page: "/test_resources?page=2" )) subject.fetch(true) @@ -476,8 +474,8 @@ def to_proc context "from prev_page" do before(:each) do stub_json_request(:get, %r{test_resources}, json( - :test_resources => [{ :id => 2 }], - :previous_page => "/test_resources?page=1" + test_resources: [{id: 2}], + previous_page: "/test_resources?page=1" )) subject.fetch(true) @@ -491,7 +489,7 @@ def to_proc context "with nothing" do before(:each) do - stub_json_request(:get, %r{test_resources}, json(:test_resources => [{ :id => 2 }])) + stub_json_request(:get, %r{test_resources}, json(test_resources: [{id: 2}])) subject.fetch(true) @next_page = subject.instance_variable_get(:@options)["next_page"] end @@ -504,7 +502,7 @@ def to_proc context "with client error" do before(:each) do - stub_request(:get, %r{test_resources}).to_return(:status => 500) + stub_request(:get, %r{test_resources}).to_return(status: 500) end it "should properly be handled" do @@ -515,8 +513,8 @@ def to_proc context "with an invalid model key expectation" do before(:each) do stub_json_request(:get, %r{test_resources}, json( - :test_resource_stuff => [{ :id => 2 }], - :next_page => "/test_resources?page=2" + test_resource_stuff: [{id: 2}], + next_page: "/test_resources?page=2" )) end @@ -527,7 +525,7 @@ def to_proc context "with nil body" do before(:each) do - stub_request(:get, %r{test_resources}).to_return(:status => 200) + stub_request(:get, %r{test_resources}).to_return(status: 200) end it "should properly be handled" do @@ -549,14 +547,14 @@ def to_proc { "meta" => { "has_more" => true, - "after_cursor" => 'after_cursor', - "before_cursor" => 'before_cursor' + "after_cursor" => "after_cursor", + "before_cursor" => "before_cursor" }, "links" => { "next" => "next_page", "prev" => "previous_page" }, - "test_resources" => [{ "id" => 1 }] + "test_resources" => [{"id" => 1}] } end before do @@ -574,19 +572,19 @@ def to_proc end context "save" do - let(:options) { { :abc => 1 } } + let(:options) { {abc: 1} } before(:each) do - stub_json_request(:get, %r{test_resources}, json(:test_resources => [])) + stub_json_request(:get, %r{test_resources}, json(test_resources: [])) subject.clear_cache end context "with a hash" do - let(:object) { double('ZendeskAPI::TestResource', :changes => [:xxx], :changed? => true, :destroyed? => false) } + let(:object) { double("ZendeskAPI::TestResource", changes: [:xxx], changed?: true, destroyed?: false) } it "should call create with those options" do - expect(ZendeskAPI::TestResource).to receive(:new). - with(client, options.merge(:association => subject.association)). - and_return(object) + expect(ZendeskAPI::TestResource).to receive(:new) + .with(client, options.merge(association: subject.association)) + .and_return(object) subject << options @@ -615,10 +613,10 @@ def to_proc context "with everything else" do it "should pass to new, since this is how attachment handles it" do - attachment = double(:changes => [:xxx], :changed? => true, :destroyed? => false) - expect(ZendeskAPI::TestResource).to receive(:new). - with(client, :id => "img.jpg", :association => instance_of(ZendeskAPI::Association)). - and_return attachment + attachment = double(changes: [:xxx], changed?: true, destroyed?: false) + expect(ZendeskAPI::TestResource).to receive(:new) + .with(client, id: "img.jpg", association: instance_of(ZendeskAPI::Association)) + .and_return attachment subject << "img.jpg" @@ -654,9 +652,9 @@ def to_proc before(:each) do stub_json_request(:get, %r{users\?page=2}, json( - :users => [{ :id => 2 }], - :next_page => "/users?page=3&per_page=1", - :previous_page => "/users?page=1&per_page=1" + users: [{id: 2}], + next_page: "/users?page=3&per_page=1", + previous_page: "/users?page=1&per_page=1" )) subject.per_page(1).page(2) @@ -665,7 +663,7 @@ def to_proc context "pagination with no options" do before(:each) do - stub_json_request(:get, %r{users\?page=(1|3)}, json(:users => [{ :id => 3 }])) + stub_json_request(:get, %r{users\?page=(1|3)}, json(users: [{id: 3}])) subject.per_page(nil).page(nil) end @@ -721,8 +719,8 @@ def to_proc ZendeskAPI::TestResource.has ZendeskAPI::NilResource stub_json_request(:get, %r{test_resources\?include=nil_resources}, json( - :test_resources => [{ :id => 1, :nil_resource_id => 4 }], - :nil_resources => [{ :id => 1, :name => :bye }, { :id => 4, :name => :hi }] + test_resources: [{id: 1, nil_resource_id: 4}], + nil_resources: [{id: 1, name: :bye}, {id: 4, name: :hi}] )) subject.fetch(true) @@ -747,9 +745,10 @@ def to_proc :get, %r{test_resources\?include=nil_resources}, json( - :test_resources => [{ :id => 1, :nil_resource_id => 4 }, { :id => 2, :nil_resource_id => 1 }], - :nil_resources => [{ :id => 1, :name => :bye }, { :id => 4, :name => :hi }] - )) + test_resources: [{id: 1, nil_resource_id: 4}, {id: 2, nil_resource_id: 1}], + nil_resources: [{id: 1, name: :bye}, {id: 4, name: :hi}] + ) + ) subject.fetch(true) end @@ -786,12 +785,12 @@ def to_proc stub_json_request( :get, %r{test_resources\?include=nil_resources}, - json(:test_resources => [{ :id => 1, :nil_resource_ids => [1, 4] }], - :nil_resources => [ - { :id => 1, :name => :hi }, - { :id => 4, :name => :hello }, - { :id => 5, :name => :goodbye } - ]) + json(test_resources: [{id: 1, nil_resource_ids: [1, 4]}], + nil_resources: [ + {id: 1, name: :hi}, + {id: 4, name: :hello}, + {id: 5, name: :goodbye} + ]) ) subject.fetch(true) @@ -804,7 +803,7 @@ def to_proc end it "should side load the correct nil_resources" do - expect(@resource.nil_resources.map(&:name)).to eq(%w{hi hello}) + expect(@resource.nil_resources.map(&:name)).to eq(%w[hi hello]) end end @@ -815,12 +814,13 @@ def to_proc stub_json_request( :get, %r{test_resources\?include=nil_resources}, - json(:test_resources => [{ :id => 1 }], - :nil_resources => [ - { :id => 1, :test_resource_id => 2 }, - { :id => 2, :test_resource_id => 1 }, - { :id => 4, :test_resource_id => 1 } - ])) + json(test_resources: [{id: 1}], + nil_resources: [ + {id: 1, test_resource_id: 2}, + {id: 2, test_resource_id: 1}, + {id: 4, test_resource_id: 1} + ]) + ) subject.fetch(true) @resource = subject.detect { |res| res.id == 1 } @@ -840,10 +840,10 @@ def to_proc ZendeskAPI::TestResource.has ZendeskAPI::NilResource stub_json_request(:get, %r{test_resources\?include=nil_resources}, - json( - :test_resources => [{ :id => 1 }], - :nil_resources => [{ :id => 1, :test_resource_id => 2 }, { :id => 2, :test_resource_id => 1 }] - )) + json( + test_resources: [{id: 1}], + nil_resources: [{id: 1, test_resource_id: 2}, {id: 2, test_resource_id: 1}] + )) subject.fetch(true) @resource = subject.detect { |res| res.id == 1 } @@ -860,11 +860,11 @@ def to_proc context "with name as key" do before(:each) do - ZendeskAPI::TestResource.has ZendeskAPI::NilResource, :include_key => :name + ZendeskAPI::TestResource.has ZendeskAPI::NilResource, include_key: :name stub_json_request(:get, %r{test_resources\?include=nil_resources}, json( - :test_resources => [{ :id => 1, :nil_resource_id => 4 }], - :nil_resources => [{ :name => 1 }, { :name => 4 }] + test_resources: [{id: 1, nil_resource_id: 4}], + nil_resources: [{name: 1}, {name: 4}] )) subject.fetch(true) @@ -887,8 +887,8 @@ def to_proc ZendeskAPI::TestResource::TestChild.has ZendeskAPI::NilResource stub_json_request(:get, %r{test_resources\?include=nil_resources}, json( - :test_resources => [{ :id => 1, :test_child => { :nil_resource_id => 4 } }], - :nil_resources => [{ :id => 1 }, { :id => 4 }] + test_resources: [{id: 1, test_child: {nil_resource_id: 4}}], + nil_resources: [{id: 1}, {id: 4}] )) subject.fetch(true) @@ -933,10 +933,10 @@ def to_proc end context "with a module (Search)" do - subject { ZendeskAPI::Collection.new(client, ZendeskAPI::Search, :query => "hello") } + subject { ZendeskAPI::Collection.new(client, ZendeskAPI::Search, query: "hello") } before(:each) do - stub_json_request(:get, %r{search\?query=hello}, json(:results => [])) + stub_json_request(:get, %r{search\?query=hello}, json(results: [])) stub_request(:get, %r{search\?page%5Bsize%5D=100&query=hello}).to_raise(ZendeskAPI::Error::NetworkError) end @@ -946,21 +946,21 @@ def to_proc end context "with a module (SearchExport)" do - subject { ZendeskAPI::Collection.new(client, ZendeskAPI::SearchExport, :query => "hello") } + subject { ZendeskAPI::Collection.new(client, ZendeskAPI::SearchExport, query: "hello") } before(:each) do stub_request(:get, %r{search/export\?page%5Bsize%5D=100&query=hello}).to_raise(ZendeskAPI::Error::NetworkError) end it "should not blow up" do - stub_json_request(:get, %r{search/export\?query=hello}, json(:results => [])) + stub_json_request(:get, %r{search/export\?query=hello}, json(results: [])) expect(subject.to_a).to eq([]) end it "should not have more results" do - stub_json_request(:get, %r{search/export\?query=hello}, json(:results => [], - :meta => { has_more: false })) + stub_json_request(:get, %r{search/export\?query=hello}, json(results: [], + meta: {has_more: false})) subject.fetch response = subject.instance_variable_get(:@response).body @@ -969,9 +969,9 @@ def to_proc end it "should not have more pages data" do - stub_json_request(:get, %r{search/export\?query=hello}, json(:results => [], - :meta => { has_more: false }, - :links => { :next => nil })) + stub_json_request(:get, %r{search/export\?query=hello}, json(results: [], + meta: {has_more: false}, + links: {next: nil})) subject.fetch response = subject.instance_variable_get(:@response).body @@ -981,7 +981,7 @@ def to_proc context "with different path" do subject do - ZendeskAPI::Collection.new(client, ZendeskAPI::TestResource, :collection_path => %w(test_resources active)) + ZendeskAPI::Collection.new(client, ZendeskAPI::TestResource, collection_path: %w[test_resources active]) end before(:each) do @@ -997,7 +997,7 @@ def to_proc context "resources" do before(:each) do stub_json_request(:get, %r{test_resources/active}, - json(:test_resources => [{ :id => 1 }])) + json(test_resources: [{id: 1}])) subject.fetch @@ -1024,7 +1024,7 @@ def to_proc "next" => "https://test_resources.json?page[after]=#{page2_cursor}&page[size]=100", "prev" => nil }, - "test_resources" => [{ "id" => 1 }] + "test_resources" => [{"id" => 1}] } end @@ -1034,7 +1034,7 @@ def to_proc context "when we know for sure that the endpoint does not support CBP" do before do - stub_json_request(:get, %r{test_resources/show_many}, json(:test_resources => [{ :id => 1 }])) + stub_json_request(:get, %r{test_resources/show_many}, json(test_resources: [{id: 1}])) end it "does not try to default to CBP" do @@ -1051,13 +1051,13 @@ def to_proc it "tries to make a CBP request, setting the page[size] parameter" do subject.fetch - expect(subject.instance_variable_get(:@options)["page"]).to eq({ "size" => 100, "after" => page2_cursor, "before" => nil }) + expect(subject.instance_variable_get(:@options)["page"]).to eq({"size" => 100, "after" => page2_cursor, "before" => nil}) end context "when per_page is given" do it "tries the CBP request with the given page size" do subject.per_page(22).fetch - expect(subject.instance_variable_get(:@options)["page"]).to eq({ "size" => 22, "after" => page2_cursor, "before" => nil }) + expect(subject.instance_variable_get(:@options)["page"]).to eq({"size" => 22, "after" => page2_cursor, "before" => nil}) end end end @@ -1072,9 +1072,9 @@ def generate_response(index, has_more) }, "links" => { "next" => has_more ? "https://test_resources.json?page%5Bafter%5D=after#{index}&page%5Bsize%5D=1" : nil, - "prev" => index > 1 ? "https://test_resources.json?page%5Bafter%5D=after#{index - 1}&page%5Bsize%5D=1" : nil + "prev" => (index > 1) ? "https://test_resources.json?page%5Bafter%5D=after#{index - 1}&page%5Bsize%5D=1" : nil }, - "test_resources" => [{ "id" => index }] + "test_resources" => [{"id" => index}] } end before do @@ -1089,10 +1089,10 @@ def generate_response(index, has_more) expect do |b| silence_logger { subject.per_page(1).all(&b) } end.to yield_successive_args( - [ZendeskAPI::TestResource.new(client, id: 1), { "after" => "after1", "before" => "before0", "size" => 1 }], - [ZendeskAPI::TestResource.new(client, id: 2), { "after" => "after2", "before" => "before1", "size" => 1 }], - [ZendeskAPI::TestResource.new(client, id: 3), { "after" => "after3", "before" => "before2", "size" => 1 }], - [ZendeskAPI::TestResource.new(client, id: 4), { "after" => "after4", "before" => "before3", "size" => 1 }] + [ZendeskAPI::TestResource.new(client, id: 1), {"after" => "after1", "before" => "before0", "size" => 1}], + [ZendeskAPI::TestResource.new(client, id: 2), {"after" => "after2", "before" => "before1", "size" => 1}], + [ZendeskAPI::TestResource.new(client, id: 3), {"after" => "after3", "before" => "before2", "size" => 1}], + [ZendeskAPI::TestResource.new(client, id: 4), {"after" => "after4", "before" => "before3", "size" => 1}] ) end end diff --git a/spec/core/configuration_spec.rb b/spec/core/configuration_spec.rb index 5166f47f..04521698 100644 --- a/spec/core/configuration_spec.rb +++ b/spec/core/configuration_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - describe ZendeskAPI::Configuration do subject { ZendeskAPI::Configuration.new } @@ -10,7 +8,7 @@ end it "should set accept header properly" do - expect(subject.options[:headers][:accept]).to eq('application/json') + expect(subject.options[:headers][:accept]).to eq("application/json") end it "should set user agent header properly" do @@ -26,7 +24,7 @@ end it "should merge options with client_options" do - subject.client_options = { :ssl => { :verify => false } } + subject.client_options = {ssl: {verify: false}} expect(subject.options[:ssl][:verify]).to eq(false) end diff --git a/spec/core/create_resource_spec.rb b/spec/core/create_resource_spec.rb index 32146f21..7f06ab67 100644 --- a/spec/core/create_resource_spec.rb +++ b/spec/core/create_resource_spec.rb @@ -1,12 +1,10 @@ -require 'core/spec_helper' - describe ZendeskAPI::CreateResource do context "create" do - let(:attr) { { :test_field => "blah" } } + let(:attr) { {test_field: "blah"} } subject { ZendeskAPI::TestResource } before(:each) do - stub_request(:post, %r{test_resources}).to_return(:body => json) + stub_request(:post, %r{test_resources}).to_return(body: json) end it "should return instance of resource" do @@ -15,7 +13,7 @@ context "with client error" do before(:each) do - stub_request(:post, %r{test_resources}).to_return(:status => 500) + stub_request(:post, %r{test_resources}).to_return(status: 500) end it "should handle it properly" do @@ -28,11 +26,11 @@ subject { ZendeskAPI::TestResource } before(:each) do - stub_request(:post, %r{test_resources}).to_return(:status => 500) + stub_request(:post, %r{test_resources}).to_return(status: 500) end it "should raise if save fails" do - expect { subject.create!(client, :test_field => "blah") }.to raise_error(ZendeskAPI::Error::NetworkError) + expect { subject.create!(client, test_field: "blah") }.to raise_error(ZendeskAPI::Error::NetworkError) end end end diff --git a/spec/core/data_namespace_spec.rb b/spec/core/data_namespace_spec.rb index 6d83d273..7dff935e 100644 --- a/spec/core/data_namespace_spec.rb +++ b/spec/core/data_namespace_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - class ZendeskAPI::DataNamespaceTest; end describe ZendeskAPI::DataNamespace do @@ -7,8 +5,8 @@ class ZendeskAPI::DataNamespaceTest; end let(:target_klass) { ZendeskAPI::DataNamespaceTest } it "adds class to its descendants list when included" do expect(ZendeskAPI::DataNamespace.descendants).not_to include(target_klass) - expect { target_klass.send(:include, ZendeskAPI::DataNamespace) }. - to change { ZendeskAPI::DataNamespace.descendants.count }.by(1) + expect { target_klass.send(:include, ZendeskAPI::DataNamespace) } + .to change { ZendeskAPI::DataNamespace.descendants.count }.by(1) expect(ZendeskAPI::DataNamespace.descendants).to include(target_klass) end end diff --git a/spec/core/data_resource_spec.rb b/spec/core/data_resource_spec.rb index 53643d91..f59254e4 100644 --- a/spec/core/data_resource_spec.rb +++ b/spec/core/data_resource_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - describe ZendeskAPI::DataResource do specify "singular resource name" do expect(ZendeskAPI::Ticket.singular_resource_name).to eq("ticket") @@ -13,21 +11,21 @@ end context "association" do - subject { ZendeskAPI::TestResource.new(client, :id => 1) } + subject { ZendeskAPI::TestResource.new(client, id: 1) } let(:options) { {} } before(:each) do - ZendeskAPI::TestResource.has :nil, options.merge(:class => ZendeskAPI::NilDataResource) + ZendeskAPI::TestResource.has :nil, options.merge(class: ZendeskAPI::NilDataResource) end it "should try and find non-existent object" do - stub_json_request(:get, %r{test_resources/1/nil}, json(:nil_data_resource => {})) + stub_json_request(:get, %r{test_resources/1/nil}, json(nil_data_resource: {})) expect(subject.nil).to be_instance_of(ZendeskAPI::NilDataResource) end context "inline => true" do - let(:options) { { :inline => true } } + let(:options) { {inline: true} } it "should not try and find non-existent object" do subject.nil @@ -90,7 +88,7 @@ end context "with explicit class name" do - before(:all) { ZendeskAPI::TestResource.has :baz, :class => ZendeskAPI::TestResource } + before(:all) { ZendeskAPI::TestResource.has :baz, class: ZendeskAPI::TestResource } it "should define a method with the same name" do expect(subject.instance_methods.map(&:to_s)).to include("baz") @@ -100,8 +98,8 @@ context "instance method" do context "with no side-loading" do - subject { ZendeskAPI::TestResource.new(client, :id => 1, :test_resource_id => 1) } - before(:each) { stub_json_request(:get, %r{test_resources/\d+}, json(:test_resource => {})) } + subject { ZendeskAPI::TestResource.new(client, id: 1, test_resource_id: 1) } + before(:each) { stub_json_request(:get, %r{test_resources/\d+}, json(test_resource: {})) } it "should attempt to grab the resource from the host" do expect(subject.test_resource).to be_instance_of(ZendeskAPI::TestResource) @@ -112,7 +110,7 @@ end context "with a client error" do - before(:each) { stub_request(:get, %r{test_resources/\d+}).to_return(:status => 500) } + before(:each) { stub_request(:get, %r{test_resources/\d+}).to_return(status: 500) } it "should handle it properly" do expect { silence_logger { expect(subject.test_resource).to be_nil } }.to_not raise_error @@ -121,8 +119,8 @@ context "with an explicit path set" do before(:each) do - ZendeskAPI::TestResource.has ZendeskAPI::TestResource, :path => "blergh" - stub_json_request(:get, %r{blergh/\d+}, json(:test_resource => {})) + ZendeskAPI::TestResource.has ZendeskAPI::TestResource, path: "blergh" + stub_json_request(:get, %r{blergh/\d+}, json(test_resource: {})) end it "should call the right path" do @@ -132,8 +130,8 @@ end context "with side-loading of resource" do - let(:test_resource) { { :message => "FOO_OBJ" } } - subject { ZendeskAPI::TestResource.new(client, :test_resource => test_resource).test_resource } + let(:test_resource) { {message: "FOO_OBJ"} } + subject { ZendeskAPI::TestResource.new(client, test_resource: test_resource).test_resource } it "should load the correct instance" do expect(subject).to be_instance_of(ZendeskAPI::TestResource) @@ -145,7 +143,7 @@ end context "with side-loading of id" do - subject { ZendeskAPI::TestResource.new(client, :test_resource_id => 1) } + subject { ZendeskAPI::TestResource.new(client, test_resource_id: 1) } before(:each) do stub_json_request(:get, %r{test_resources/1}, json("test_resource" => {})) end @@ -174,7 +172,7 @@ end context "with explicit class name" do - before(:each) { ZendeskAPI::TestResource.has_many :cats, :class => ZendeskAPI::TestResource } + before(:each) { ZendeskAPI::TestResource.has_many :cats, class: ZendeskAPI::TestResource } it "should define a method with the same name" do expect(subject.instance_methods.map(&:to_s)).to include("cats") @@ -184,7 +182,7 @@ context "instance method" do context "with no side-loading" do - subject { ZendeskAPI::TestResource.new(client, :id => 1) } + subject { ZendeskAPI::TestResource.new(client, id: 1) } it "should not attempt to grab the resource from the host" do expect(subject.test_resources).to be_instance_of(ZendeskAPI::Collection) @@ -196,7 +194,7 @@ context "with an explicit path set" do before(:each) do - ZendeskAPI::TestResource.has_many ZendeskAPI::TestResource, :path => "blargh" + ZendeskAPI::TestResource.has_many ZendeskAPI::TestResource, path: "blargh" end it "should call the right path" do @@ -206,8 +204,8 @@ end context "with side-loading of resource" do - let(:test_resources) { [{ :message => "FOO_OBJ" }] } - subject { ZendeskAPI::TestResource.new(client, :test_resources => test_resources).test_resources.first } + let(:test_resources) { [{message: "FOO_OBJ"}] } + subject { ZendeskAPI::TestResource.new(client, test_resources: test_resources).test_resources.first } it "should properly create instance" do expect(subject.message).to eq("FOO_OBJ") @@ -220,7 +218,7 @@ context "with side-loading of id" do let(:test_resource_ids) { [1, 2, 3] } - subject { ZendeskAPI::TestResource.new(client, :test_resource_ids => test_resource_ids) } + subject { ZendeskAPI::TestResource.new(client, test_resource_ids: test_resource_ids) } it "should find foo_id and load it from the api" do expect(ZendeskAPI::TestResource).to receive(:find).with(client, kind_of(Hash)).exactly(test_resource_ids.length).times diff --git a/spec/core/data_spec.rb b/spec/core/data_spec.rb index a6e0cff4..5b8461ca 100644 --- a/spec/core/data_spec.rb +++ b/spec/core/data_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - RSpec.describe ZendeskAPI::Data do describe ".new_from_response" do let(:response) { double(:response) } diff --git a/spec/core/error_spec.rb b/spec/core/error_spec.rb index f39eaae5..fd714f99 100644 --- a/spec/core/error_spec.rb +++ b/spec/core/error_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - describe ZendeskAPI::Error do describe ZendeskAPI::Error::ClientError do it "works without a response" do diff --git a/spec/core/helpers_spec.rb b/spec/core/helpers_spec.rb index 3c55e9c3..f88c6f90 100644 --- a/spec/core/helpers_spec.rb +++ b/spec/core/helpers_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - RSpec.describe ZendeskAPI::Helpers do describe "#present?" do it "is false when nil, or empty" do diff --git a/spec/core/inflection_spec.rb b/spec/core/inflection_spec.rb index c13bb36b..d0d5785e 100644 --- a/spec/core/inflection_spec.rb +++ b/spec/core/inflection_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - describe String do specify "the plural of forum if forums" do expect(Inflection.plural("forum")).to eq("forums") diff --git a/spec/core/lru_cache_spec.rb b/spec/core/lru_cache_spec.rb index fb58ec55..3b831ac1 100644 --- a/spec/core/lru_cache_spec.rb +++ b/spec/core/lru_cache_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - describe ZendeskAPI::LRUCache do let(:cache) { ZendeskAPI::LRUCache.new(2) } diff --git a/spec/core/middleware/request/api_token_impersonate_spec.rb b/spec/core/middleware/request/api_token_impersonate_spec.rb index 39c43afe..475ea7d0 100644 --- a/spec/core/middleware/request/api_token_impersonate_spec.rb +++ b/spec/core/middleware/request/api_token_impersonate_spec.rb @@ -1,11 +1,11 @@ -require 'core/spec_helper' +require "core/spec_helper" RSpec.describe ZendeskAPI::Middleware::Request::ApiTokenImpersonate do let(:app) { ->(env) { env } } let(:middleware) { described_class.new(app) } - let(:username) { 'impersonated_user' } - let(:token) { 'abc123' } - let(:original_username) { 'original_user/token' } + let(:username) { "impersonated_user" } + let(:token) { "abc123" } + let(:original_username) { "original_user/token" } let(:encoded_auth) { Base64.urlsafe_encode64("#{original_username}:#{token}") } let(:env) do { @@ -17,8 +17,8 @@ after { Thread.current[:zendesk_thread_local_username] = nil } - context 'when local_username is set and authorization is a valid API token' do - it 'impersonates the user by modifying the Authorization header' do + context "when local_username is set and authorization is a valid API token" do + it "impersonates the user by modifying the Authorization header" do Thread.current[:zendesk_thread_local_username] = username result = middleware.call(env) new_auth = result[:request_headers][:authorization] @@ -27,37 +27,37 @@ end end - context 'when local_username is not set' do - it 'does not modify the Authorization header' do + context "when local_username is not set" do + it "does not modify the Authorization header" do result = middleware.call(env) expect(result[:request_headers][:authorization]).to eq(env[:request_headers][:authorization]) end end - context 'when authorization header is not Basic' do - it 'does not modify the Authorization header' do + context "when authorization header is not Basic" do + it "does not modify the Authorization header" do Thread.current[:zendesk_thread_local_username] = username - env[:request_headers][:authorization] = 'Bearer something' + env[:request_headers][:authorization] = "Bearer something" result = middleware.call(env) - expect(result[:request_headers][:authorization]).to eq('Bearer something') + expect(result[:request_headers][:authorization]).to eq("Bearer something") end end - context 'when authorization does not contain /token:' do - it 'raises an error' do + context "when authorization does not contain /token:" do + it "raises an error" do Thread.current[:zendesk_thread_local_username] = username - env[:request_headers][:authorization] = "Basic #{Base64.urlsafe_encode64('user:abc123')}" + env[:request_headers][:authorization] = "Basic #{Base64.urlsafe_encode64("user:abc123")}" result = middleware.call(env) - expect(result[:request_headers][:authorization]).to eq("Basic #{Base64.urlsafe_encode64('user:abc123')}") + expect(result[:request_headers][:authorization]).to eq("Basic #{Base64.urlsafe_encode64("user:abc123")}") end end - context 'when authorization is not in valid format' do - it 'raises an error' do + context "when authorization is not in valid format" do + it "raises an error" do Thread.current[:zendesk_thread_local_username] = username - env[:request_headers][:authorization] = "Basic #{Base64.urlsafe_encode64('user/token:abc123:extra')}" + env[:request_headers][:authorization] = "Basic #{Base64.urlsafe_encode64("user/token:abc123:extra")}" result = middleware.call(env) - expect(result[:request_headers][:authorization]).to eq("Basic #{Base64.urlsafe_encode64('user/token:abc123:extra')}") + expect(result[:request_headers][:authorization]).to eq("Basic #{Base64.urlsafe_encode64("user/token:abc123:extra")}") end end end diff --git a/spec/core/middleware/request/encode_json_spec.rb b/spec/core/middleware/request/encode_json_spec.rb index 2402b217..f58aac02 100644 --- a/spec/core/middleware/request/encode_json_spec.rb +++ b/spec/core/middleware/request/encode_json_spec.rb @@ -1,76 +1,74 @@ -require 'core/spec_helper' - describe ZendeskAPI::Middleware::Request::EncodeJson do let(:app) do ZendeskAPI::Middleware::Request::EncodeJson.new(lambda { |x| x }) end - let(:response) { app.call({ :request_headers => {} }.merge(env)) } + let(:response) { app.call({request_headers: {}}.merge(env)) } - context 'with a nil body' do - let(:env) { { :body => nil } } + context "with a nil body" do + let(:env) { {body: nil} } - it 'should not return json' do + it "should not return json" do expect(response[:body]).to be_nil end end - context 'with an empty body' do - let(:env) { { :body => '' } } + context "with an empty body" do + let(:env) { {body: ""} } - it 'should not return json' do - expect(response[:body]).to eq('') + it "should not return json" do + expect(response[:body]).to eq("") end end - context 'with a proper mime type' do - context 'empty' do - let(:env) { { :body => { :a => :b } } } + context "with a proper mime type" do + context "empty" do + let(:env) { {body: {a: :b}} } - it 'encodes json' do - expect(response[:body]).to eq(JSON.dump(:a => :b)) + it "encodes json" do + expect(response[:body]).to eq(JSON.dump(a: :b)) end - it 'sets the content type' do - expect(response[:request_headers]['Content-Type']).to eq('application/json') + it "sets the content type" do + expect(response[:request_headers]["Content-Type"]).to eq("application/json") end end - context 'application/json' do + context "application/json" do let(:env) { { - :body => { :a => :b }, - :request_headers => { - 'Content-Type' => 'application/json' + body: {a: :b}, + request_headers: { + "Content-Type" => "application/json" } } } - it 'encodes json' do - expect(response[:body]).to eq(JSON.dump(:a => :b)) + it "encodes json" do + expect(response[:body]).to eq(JSON.dump(a: :b)) end - it 'keeps the content type' do - expect(response[:request_headers]['Content-Type']).to eq('application/json') + it "keeps the content type" do + expect(response[:request_headers]["Content-Type"]).to eq("application/json") end end - context 'application/json; encoding=utf-8' do + context "application/json; encoding=utf-8" do let(:env) { { - :body => { :a => :b }, - :request_headers => { - 'Content-Type' => 'application/json; encoding=utf-8' + body: {a: :b}, + request_headers: { + "Content-Type" => "application/json; encoding=utf-8" } } } - it 'encodes json' do - expect(response[:body]).to eq(JSON.dump(:a => :b)) + it "encodes json" do + expect(response[:body]).to eq(JSON.dump(a: :b)) end - it 'keeps the content type' do - expect(response[:request_headers]['Content-Type']).to eq('application/json; encoding=utf-8') + it "keeps the content type" do + expect(response[:request_headers]["Content-Type"]).to eq("application/json; encoding=utf-8") end end end diff --git a/spec/core/middleware/request/etag_cache_spec.rb b/spec/core/middleware/request/etag_cache_spec.rb index 9c2fdfa5..af01f742 100644 --- a/spec/core/middleware/request/etag_cache_spec.rb +++ b/spec/core/middleware/request/etag_cache_spec.rb @@ -1,20 +1,18 @@ -require 'core/spec_helper' - describe ZendeskAPI::Middleware::Request::EtagCache do it "caches" do client.config.cache.size = 1 - stub_json_request(:get, %r{blergh}, '{"x":1}', :headers => { "Etag" => "x" }) + stub_json_request(:get, %r{blergh}, '{"x":1}', headers: {"Etag" => "x"}) first_response = client.connection.get("blergh") expect(first_response.status).to eq(200) - expect(first_response.body).to eq({ "x" => 1 }) + expect(first_response.body).to eq({"x" => 1}) - stub_request(:get, %r{blergh}).to_return(:status => 304, :headers => { "Etag" => "x" }) + stub_request(:get, %r{blergh}).to_return(status: 304, headers: {"Etag" => "x"}) response = client.connection.get("blergh") expect(response.status).to eq(304) - expect(response.body).to eq({ "x" => 1 }) + expect(response.body).to eq({"x" => 1}) - %w{content_encoding content_type content_length etag}.each do |header| + %w[content_encoding content_type content_length etag].each do |header| expect(response.headers[header]).to eq(first_response.headers[header]) end end diff --git a/spec/core/middleware/request/raise_rate_limited_spec.rb b/spec/core/middleware/request/raise_rate_limited_spec.rb index 94b9ef9b..cfb6b9ca 100644 --- a/spec/core/middleware/request/raise_rate_limited_spec.rb +++ b/spec/core/middleware/request/raise_rate_limited_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - describe ZendeskAPI::Middleware::Request::RaiseRateLimited do before do client.config.retry = false @@ -8,19 +6,19 @@ stub_request(:get, /blergh/).to_return(status: 429) end - it 'should raise RateLimited' do + it "should raise RateLimited" do expect do - client.connection.get('blergh') + client.connection.get("blergh") end.to raise_error(ZendeskAPI::Error::RateLimited) end - it 'should print to logger' do + it "should print to logger" do expect(client.config.logger).to receive(:warn) - client.connection.get('blergh') rescue ZendeskAPI::Error::RateLimited # rubocop:disable Style/RescueModifier + client.connection.get("blergh") rescue ZendeskAPI::Error::RateLimited # rubocop:disable Style/RescueModifier end - it 'should not fail without a logger', :prevent_logger_changes do + it "should not fail without a logger", :prevent_logger_changes do client.config.logger = false - client.connection.get('blergh') rescue ZendeskAPI::Error::RateLimited # rubocop:disable Style/RescueModifier + client.connection.get("blergh") rescue ZendeskAPI::Error::RateLimited # rubocop:disable Style/RescueModifier end end diff --git a/spec/core/middleware/request/retry_spec.rb b/spec/core/middleware/request/retry_spec.rb index 5a542150..627a83f1 100644 --- a/spec/core/middleware/request/retry_spec.rb +++ b/spec/core/middleware/request/retry_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - describe ZendeskAPI::Middleware::Request::Retry do def runtime start = Time.now.to_f @@ -9,9 +7,9 @@ def runtime [429, 503].each do |error_code| it "should wait requisite seconds and then retry request on #{error_code}" do - stub_request(:get, %r{blergh}). - to_return(:status => 429, :headers => { :retry_after => 1 }). - to_return(:status => 200) + stub_request(:get, %r{blergh}) + .to_return(status: 429, headers: {retry_after: 1}) + .to_return(status: 200) seconds = runtime { expect(client.connection.get("blergh").status).to eq(200) @@ -38,7 +36,7 @@ def runtime context "connection failed" do before(:each) do client.config.retry_on_exception = true - stub_request(:any, /.*/).to_raise(Faraday::ConnectionFailed).to_return(:status => 200) + stub_request(:any, /.*/).to_raise(Faraday::ConnectionFailed).to_return(status: 200) end it "should raise NetworkError, but then actually retry" do @@ -52,7 +50,7 @@ def runtime context "connection failed" do before(:each) do client.config.retry_on_exception = false - stub_request(:any, /.*/).to_raise(Faraday::ConnectionFailed).to_return(:status => 200) + stub_request(:any, /.*/).to_raise(Faraday::ConnectionFailed).to_return(status: 200) end it "should raise NetworkError, but never retry" do @@ -65,9 +63,9 @@ def runtime [503].each do |error_code| context "with failing request because server is not ready with default error code #{error_code}", :prevent_logger_changes do before do - stub_request(:get, %r{blergh}). - to_return(:status => error_code). - to_return(:status => 200) + stub_request(:get, %r{blergh}) + .to_return(status: error_code) + .to_return(status: 200) expect_any_instance_of(ZendeskAPI::Middleware::Request::Retry).to receive(:sleep).exactly(10).times.with(1) end @@ -84,7 +82,7 @@ def runtime end it "should not fail without a logger" do - client.config.logger = false + client.config.logger = nil client.connection.get("blergh") end end @@ -94,9 +92,9 @@ def runtime context "with failing request because server is not ready with default error code #{error_code}", :prevent_logger_changes do before do client.config.retry_codes = [501, 503] - stub_request(:get, %r{blergh}). - to_return(:status => error_code). - to_return(:status => 200) + stub_request(:get, %r{blergh}) + .to_return(status: error_code) + .to_return(status: 200) expect_any_instance_of(ZendeskAPI::Middleware::Request::Retry).to receive(:sleep).exactly(10).times.with(1) end @@ -113,7 +111,7 @@ def runtime end it "should not fail without a logger" do - client.config.logger = false + client.config.logger = nil client.connection.get("blergh") end end diff --git a/spec/core/middleware/request/upload_spec.rb b/spec/core/middleware/request/upload_spec.rb index 9175a586..9e3b8f1f 100644 --- a/spec/core/middleware/request/upload_spec.rb +++ b/spec/core/middleware/request/upload_spec.rb @@ -1,27 +1,26 @@ -require 'core/spec_helper' -require 'tempfile' -require 'action_dispatch' +require "tempfile" +require "action_dispatch" describe ZendeskAPI::Middleware::Request::Upload do subject { ZendeskAPI::Middleware::Request::Upload.new(lambda { |env| env }) } - let(:filename) { File.join(File.dirname(__FILE__), "test.jpg") } + let(:filename) { File.join(__dir__, "test.jpg") } it "should handle no body" do expect(subject.call({})).to eq({}) end it "should handle body with no file" do - expect(subject.call(:body => {})[:body]).to eq({}) + expect(subject.call(body: {})[:body]).to eq({}) end it "should handle invalid types" do expect(subject).to receive(:warn) - expect(subject.call(:body => { :file => :invalid })[:body]).to eq({}) + expect(subject.call(body: {file: :invalid})[:body]).to eq({}) end context "with file string" do before(:each) do - @env = subject.call(:body => { :file => filename }) + @env = subject.call(body: {file: filename}) end it "should convert file string to UploadIO" do @@ -38,7 +37,7 @@ context "with filename" do before(:each) do - @env = subject.call(:body => { :file => filename, :filename => "test" }) + @env = subject.call(body: {file: filename, filename: "test"}) end it "should not change filename" do @@ -49,8 +48,8 @@ context "with an ActionDispatch::Http::UploadedFile" do before(:each) do - @upload = ActionDispatch::Http::UploadedFile.new(:filename => "hello.jpg", :tempfile => Tempfile.new(['hello', '.jpg'])) - @env = subject.call(:body => { :file => @upload }) + @upload = ActionDispatch::Http::UploadedFile.new(filename: "hello.jpg", tempfile: Tempfile.new(["hello", ".jpg"])) + @env = subject.call(body: {file: @upload}) end it "should convert file string to UploadIO" do @@ -76,10 +75,10 @@ end it "should use the content_type of ActionDispatch::Http::UploadedFile " do - @upload.content_type = 'application/random' + @upload.content_type = "application/random" - env = subject.call(:body => { :file => @upload }) - expect(env[:body][:uploaded_data].content_type).to eq('application/random') + env = subject.call(body: {file: @upload}) + expect(env[:body][:uploaded_data].content_type).to eq("application/random") end end end @@ -87,7 +86,7 @@ context "with a Tempfile" do before(:each) do @tempfile = Tempfile.new(File.basename(filename)) - @env = subject.call(:body => { :file => @tempfile }) + @env = subject.call(body: {file: @tempfile}) end it "should convert file string to UploadIO" do @@ -106,7 +105,7 @@ context "with file instance" do context "top-level" do before(:each) do - @env = subject.call(:body => { :file => File.new(filename) }) + @env = subject.call(body: {file: File.new(filename)}) end it "should convert file string to UploadIO" do @@ -123,7 +122,7 @@ context "with filename" do before(:each) do - @env = subject.call(:body => { :file => File.new(filename), :filename => "test" }) + @env = subject.call(body: {file: File.new(filename), filename: "test"}) end it "should not change filename" do @@ -135,7 +134,7 @@ context "underneath a key" do context "only a file" do before(:each) do - @env = subject.call(:body => { :user => { :photo => File.new(filename) } }) + @env = subject.call(body: {user: {photo: File.new(filename)}}) end it "should convert file string to UploadIO" do @@ -149,7 +148,7 @@ context "with filename" do before(:each) do - @env = subject.call(:body => { :user => { :photo => { :file => File.new(filename), :filename => "test" } } }) + @env = subject.call(body: {user: {photo: {file: File.new(filename), filename: "test"}}}) end it "should convert file string to UploadIO" do diff --git a/spec/core/middleware/response/callback_spec.rb b/spec/core/middleware/response/callback_spec.rb index 06b935de..705ea63f 100644 --- a/spec/core/middleware/response/callback_spec.rb +++ b/spec/core/middleware/response/callback_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - describe ZendeskAPI::Middleware::Response::Callback do let(:response) { "TEST" } @@ -8,7 +6,7 @@ env[:body] = response end - stub_request(:get, %r{test_endpoint}).to_return(:body => JSON.dump({ "ABC" => "DEF" })) + stub_request(:get, %r{test_endpoint}).to_return(body: JSON.dump({"ABC" => "DEF"})) end it "should call callbacks " do diff --git a/spec/core/middleware/response/deflate_spec.rb b/spec/core/middleware/response/deflate_spec.rb index ad26b36d..05d5f6cd 100644 --- a/spec/core/middleware/response/deflate_spec.rb +++ b/spec/core/middleware/response/deflate_spec.rb @@ -1,21 +1,19 @@ -require 'core/spec_helper' - describe ZendeskAPI::Middleware::Response::Deflate do context "with content-encoding = 'deflate'" do subject { '{ "TESTDATA": true }' } before(:each) do stub_request(:get, %r{blergh}).to_return( - :headers => { - :content_encoding => "deflate", - :content_type => "application/json" + headers: { + content_encoding: "deflate", + content_type: "application/json" }, - :body => Zlib::Deflate.deflate(subject) + body: Zlib::Deflate.deflate(subject) ) end it "should inflate returned body" do - expect(client.connection.get("blergh").body['TESTDATA']).to be(true) + expect(client.connection.get("blergh").body["TESTDATA"]).to be(true) end end end diff --git a/spec/core/middleware/response/gzip_spec.rb b/spec/core/middleware/response/gzip_spec.rb index c1c6d86d..4e5575ad 100644 --- a/spec/core/middleware/response/gzip_spec.rb +++ b/spec/core/middleware/response/gzip_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - describe ZendeskAPI::Middleware::Response::Gzip do context "with content-encoding = 'gzip'" do subject { '{ "TESTDATA": true }' } @@ -10,16 +8,16 @@ gz.close stub_request(:get, %r{blergh}).to_return( - :headers => { - :content_encoding => "gzip", - :content_type => "application/json" + headers: { + content_encoding: "gzip", + content_type: "application/json" }, - :body => encoded_data.string + body: encoded_data.string ) end it "should inflate returned body" do - expect(client.connection.get("blergh").body['TESTDATA']).to be(true) + expect(client.connection.get("blergh").body["TESTDATA"]).to be(true) end end end diff --git a/spec/core/middleware/response/parse_iso_dates_spec.rb b/spec/core/middleware/response/parse_iso_dates_spec.rb index 9a8fca9d..e8199c78 100644 --- a/spec/core/middleware/response/parse_iso_dates_spec.rb +++ b/spec/core/middleware/response/parse_iso_dates_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - describe ZendeskAPI::Middleware::Response::ParseIsoDates do def fake_response(data) stub_json_request(:get, %r{blergh}, data) @@ -23,11 +21,11 @@ def fake_response(data) end it "should not blow up on empty body" do - expect(fake_response('').body).to eq('') + expect(fake_response("").body).to eq("") end it "should leave arrays with ids alone" do - expect(fake_response('{"x":[1,2,3]}').body).to eq({ "x" => [1, 2, 3] }) + expect(fake_response('{"x":[1,2,3]}').body).to eq({"x" => [1, 2, 3]}) end it "should not parse date-like things" do diff --git a/spec/core/middleware/response/parse_json_spec.rb b/spec/core/middleware/response/parse_json_spec.rb index ee2a5ab4..68af8e69 100644 --- a/spec/core/middleware/response/parse_json_spec.rb +++ b/spec/core/middleware/response/parse_json_spec.rb @@ -1,28 +1,26 @@ -require 'core/spec_helper' - describe ZendeskAPI::Middleware::Response::ParseJson do context "with another content-type" do before(:each) do stub_request(:get, %r{blergh}).to_return( - :headers => { - :content_type => "application/xml" + headers: { + content_type: "application/xml" }, - :body => '' + body: "" ) end it "should not return nil body" do - expect(client.connection.get("blergh").body).to eql('') + expect(client.connection.get("blergh").body).to eql("") end end context "with content-type = 'application/json'" do before(:each) do stub_request(:get, %r{blergh}).to_return( - :headers => { - :content_type => "application/json" + headers: { + content_type: "application/json" }, - :body => body + body: body ) end @@ -30,23 +28,23 @@ let(:body) { nil } it "should return empty body" do - expect(client.connection.get("blergh").body).to eql('') + expect(client.connection.get("blergh").body).to eql("") end end context "with a empty body" do - let(:body) { '' } + let(:body) { "" } it "should return empty body" do - expect(client.connection.get("blergh").body).to eql('') + expect(client.connection.get("blergh").body).to eql("") end end - context 'proper json' do + context "proper json" do let(:body) { '{ "TESTDATA": true }' } it "should parse returned body" do - expect(client.connection.get("blergh").body['TESTDATA']).to be(true) + expect(client.connection.get("blergh").body["TESTDATA"]).to be(true) end end end diff --git a/spec/core/middleware/response/raise_error_spec.rb b/spec/core/middleware/response/raise_error_spec.rb index a6c42cea..26da1b99 100644 --- a/spec/core/middleware/response/raise_error_spec.rb +++ b/spec/core/middleware/response/raise_error_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - describe ZendeskAPI::Middleware::Response::RaiseError do context "with a failed connection" do context "connection failed" do @@ -27,8 +25,8 @@ let(:body) { "" } before(:each) do - stub_request(:any, /.*/).to_return(:status => status, :body => body, - :headers => { :content_type => "application/json" }) + stub_request(:any, /.*/).to_return(status: status, body: body, + headers: {content_type: "application/json"}) end context "with status = 404" do @@ -82,7 +80,7 @@ end context "with a body" do - let(:body) { JSON.dump(:details => "hello") } + let(:body) { JSON.dump(details: "hello") } it "should return RecordInvalid with proper message" do client.connection.get "/non_existent" @@ -94,8 +92,8 @@ end { - error: 'There was an error', - errors: 'There were several errors' + error: "There was an error", + errors: "There were several errors" }.each do |key, message| context "with only an #{key} key" do let(:body) { JSON.dump(key => message) } @@ -119,7 +117,7 @@ end context "with a body" do - let(:body) { JSON.dump(:description => "big file is big", :message => "small file is small") } + let(:body) { JSON.dump(description: "big file is big", message: "small file is small") } it "should return RecordInvalid with proper message" do client.connection.get "/non_existent" @@ -131,8 +129,8 @@ end { - error: 'There was an error', - errors: 'There were several errors' + error: "There was an error", + errors: "There were several errors" }.each do |key, message| context "with only an #{key} key" do let(:body) { JSON.dump(key => message) } diff --git a/spec/core/middleware/response/sanitize_response_spec.rb b/spec/core/middleware/response/sanitize_response_spec.rb index 93247594..519ca22e 100644 --- a/spec/core/middleware/response/sanitize_response_spec.rb +++ b/spec/core/middleware/response/sanitize_response_spec.rb @@ -1,19 +1,17 @@ -require 'core/spec_helper' - describe ZendeskAPI::Middleware::Response::SanitizeResponse do def fake_response(data) stub_json_request(:get, /blergh/, data) - response = client.connection.get('blergh') + response = client.connection.get("blergh") expect(response.status).to eq(200) response end - describe 'with bad characters' do - let(:response) { fake_response("{\"x\":\"2012-02-01T13:14:15Z\", \"y\":\"\u0315\u0316\u01333\u0270\u022712awesome!" + [0xd83d, 0xdc4d].pack('U*') + "\"}") } + describe "with bad characters" do + let(:response) { fake_response("{\"x\":\"2012-02-01T13:14:15Z\", \"y\":\"\u0315\u0316\u01333\u0270\u022712awesome!" + [0xd83d, 0xdc4d].pack("U*") + "\"}") } - it 'removes bad characters' do + it "removes bad characters" do expect(response.body.to_s.valid_encoding?).to be(true) - expect(response.body['y'].to_s).to eq("\u0315\u0316\u01333\u0270\u022712awesome!") + expect(response.body["y"].to_s).to eq("\u0315\u0316\u01333\u0270\u022712awesome!") end end end diff --git a/spec/core/read_resource_spec.rb b/spec/core/read_resource_spec.rb index 2d6b01d5..044a3b64 100644 --- a/spec/core/read_resource_spec.rb +++ b/spec/core/read_resource_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - describe ZendeskAPI::ReadResource do context "find" do let(:id) { 1 } @@ -11,13 +9,13 @@ end it "should return instance of resource" do - expect(subject.find(client, :id => id)).to be_instance_of(subject) + expect(subject.find(client, id: id)).to be_instance_of(subject) end end it "should blow up without an id which would build an invalid url" do - expect{ - ZendeskAPI::User.find(client, :foo => :bar) + expect { + ZendeskAPI::User.find(client, foo: :bar) }.to raise_error("No :id given") end @@ -25,7 +23,7 @@ subject do Class.new(ZendeskAPI::TestResource) do def self.singular_resource_name - 'hello' + "hello" end def handle_response(response) @@ -35,11 +33,11 @@ def handle_response(response) end before(:each) do - stub_json_request(:get, %r{hellos/#{id}}, json(:testing => 1)) + stub_json_request(:get, %r{hellos/#{id}}, json(testing: 1)) end it "should return instance of resource" do - object = subject.find(client, :id => id) + object = subject.find(client, id: id) expect(object).to be_instance_of(subject) expect(object.testing).to eq(1) end @@ -48,12 +46,12 @@ def handle_response(response) context "with side loads" do before(:each) do stub_json_request(:get, %r{test_resources/#{id}\?include=nil_resource}, json( - "test_resource" => { :id => 1, :nil_resource_id => 2 }, - "nil_resources" => [{ :id => 1, :name => :bye }, { :id => 2, :name => :hi }] + "test_resource" => {id: 1, nil_resource_id: 2}, + "nil_resources" => [{id: 1, name: :bye}, {id: 2, name: :hi}] )) subject.has ZendeskAPI::NilResource - @resource = subject.find(client, :id => id, :include => :nil_resource) + @resource = subject.find(client, id: id, include: :nil_resource) end it "should side load nil resource" do @@ -63,13 +61,13 @@ def handle_response(response) context "with client error" do it "should handle 500 properly" do - stub_request(:get, %r{test_resources/#{id}}).to_return(:status => 500) - expect(subject.find(client, :id => id)).to eq(nil) + stub_request(:get, %r{test_resources/#{id}}).to_return(status: 500) + expect(subject.find(client, id: id)).to eq(nil) end it "should handle 404 properly" do - stub_request(:get, %r{test_resources/#{id}}).to_return(:status => 404) - expect(subject.find(client, :id => id)).to eq(nil) + stub_request(:get, %r{test_resources/#{id}}).to_return(status: 404) + expect(subject.find(client, id: id)).to eq(nil) end end end @@ -77,20 +75,20 @@ def handle_response(response) context "#reload!" do let(:id) { 2 } - subject { ZendeskAPI::TestResource.new(client, :id => id, :name => 'Old Name') } + subject { ZendeskAPI::TestResource.new(client, id: id, name: "Old Name") } before(:each) do - stub_json_request(:get, %r{test_resources/#{id}}, json("test_resource" => { :id => id, :name => "New Name" })) + stub_json_request(:get, %r{test_resources/#{id}}, json("test_resource" => {id: id, name: "New Name"})) end it "reloads the data" do - expect(subject.name).to eq('Old Name') + expect(subject.name).to eq("Old Name") assert_not_requested(:get, %r{test_resources/#{id}}) subject.reload! assert_requested(:get, %r{test_resources/#{id}}) - expect(subject.name).to eq('New Name') + expect(subject.name).to eq("New Name") end end end diff --git a/spec/core/resource_spec.rb b/spec/core/resource_spec.rb index 59f607e3..f5a4e127 100644 --- a/spec/core/resource_spec.rb +++ b/spec/core/resource_spec.rb @@ -1,11 +1,9 @@ -require 'core/spec_helper' - describe ZendeskAPI::Resource do context "initialize" do context "with :global as part of attributes" do it "should set @global_params" do - resource = ZendeskAPI::TestResource.new(client, { :global => { :something => 'hey' } }) - expect(resource.instance_variable_get(:@global_params)).to eq({ :something => 'hey' }) + resource = ZendeskAPI::TestResource.new(client, {global: {something: "hey"}}) + expect(resource.instance_variable_get(:@global_params)).to eq({something: "hey"}) end end end @@ -16,37 +14,37 @@ subject { ZendeskAPI::TestResource } before(:each) do - stub_json_request(:put, %r{test_resources/#{id}}).with(:body => json({ :test_resource => { :test => :hello } })) + stub_json_request(:put, %r{test_resources/#{id}}).with(body: json({test_resource: {test: :hello}})) end it "should return instance of resource" do - expect(subject.update(client, :id => id, :test => :hello)).to be_truthy + expect(subject.update(client, id: id, test: :hello)).to be_truthy end context "with global params" do before(:each) do - stub_json_request(:put, %r{test_resources/#{id}}).with(:body => json({ :test_resource => { :test => :hello }, :something => "something" })) + stub_json_request(:put, %r{test_resources/#{id}}).with(body: json({test_resource: {test: :hello}, something: "something"})) end it "should return instance of resource" do - expect(subject.update(client, :id => id, :test => :hello, :global => { :something => "something" })).to be_truthy + expect(subject.update(client, id: id, test: :hello, global: {something: "something"})).to be_truthy end end context "with client error" do before(:each) do - stub_request(:put, %r{test_resources/#{id}}).to_return(:status => 500) + stub_request(:put, %r{test_resources/#{id}}).to_return(status: 500) end it "should handle it properly" do - expect { silence_logger { expect(subject.update(client, :id => id)).to be(false) } }.to_not raise_error + expect { silence_logger { expect(subject.update(client, id: id)).to be(false) } }.to_not raise_error end end end context "instance method" do subject(:resource) do - ZendeskAPI::TestResource.new(client, :id => 1) + ZendeskAPI::TestResource.new(client, id: 1) end it "is delegated to the attributes" do @@ -64,29 +62,29 @@ subject { ZendeskAPI::TestResource } before(:each) do - stub_json_request(:delete, %r{test_resources/#{id}}).to_return(:status => 204) + stub_json_request(:delete, %r{test_resources/#{id}}).to_return(status: 204) end it "should return instance of resource" do - expect(subject.destroy(client, :id => id)).to be(true) + expect(subject.destroy(client, id: id)).to be(true) end context "with client error" do before(:each) do - stub_request(:delete, %r{test_resources/#{id}}).to_return(:status => 500) + stub_request(:delete, %r{test_resources/#{id}}).to_return(status: 500) end it "should handle it properly" do - expect { silence_logger { expect(subject.destroy(client, :id => id)).to be(false) } }.to_not raise_error + expect { silence_logger { expect(subject.destroy(client, id: id)).to be(false) } }.to_not raise_error end end end context "instance method" do - subject { ZendeskAPI::TestResource.new(client, :id => 1) } + subject { ZendeskAPI::TestResource.new(client, id: 1) } before(:each) do - stub_request(:delete, %r{test_resources}).to_return(:status => 204) + stub_request(:delete, %r{test_resources}).to_return(status: 204) end it "should return true and set destroyed" do @@ -97,7 +95,7 @@ context "with client error" do before(:each) do - stub_request(:delete, %r{test_resources}).to_return(:status => 500) + stub_request(:delete, %r{test_resources}).to_return(status: 500) end it "should return false and not set destroyed" do @@ -109,10 +107,10 @@ end context "#save!" do - subject { ZendeskAPI::TestResource.new(client, :id => 1) } + subject { ZendeskAPI::TestResource.new(client, id: 1) } before(:each) do - stub_request(:put, %r{test_resources/1}).to_return(:status => 422) + stub_request(:put, %r{test_resources/1}).to_return(status: 422) end it "should raise if save fails" do @@ -122,11 +120,11 @@ context "#save" do let(:id) { 1 } - let(:attr) { { :param => "test" } } - subject { ZendeskAPI::TestResource.new(client, attr.merge(:id => id)) } + let(:attr) { {param: "test"} } + subject { ZendeskAPI::TestResource.new(client, attr.merge(id: id)) } before :each do - stub_json_request(:put, %r{test_resources/#{id}}, json(:test_resource => { :param => "abc" })) + stub_json_request(:put, %r{test_resources/#{id}}, json(test_resource: {param: "abc"})) end it "should not save if already destroyed" do @@ -146,8 +144,8 @@ context "with unused associations" do before do ZendeskAPI::TestResource.associations.clear - ZendeskAPI::TestResource.has :child, :class => ZendeskAPI::TestResource::TestChild - ZendeskAPI::TestResource.has_many :children, :class => ZendeskAPI::TestResource::TestChild + ZendeskAPI::TestResource.has :child, class: ZendeskAPI::TestResource::TestChild + ZendeskAPI::TestResource.has_many :children, class: ZendeskAPI::TestResource::TestChild end it "should not touch them" do @@ -157,7 +155,7 @@ context "with client error" do before :each do - stub_request(:put, %r{test_resources/1}).to_return(:status => 500) + stub_request(:put, %r{test_resources/1}).to_return(status: 500) end it "should be properly handled" do @@ -169,7 +167,7 @@ subject { ZendeskAPI::TestResource.new(client, attr) } before :each do - stub_json_request(:post, %r{test_resources}, json(:test_resource => attr.merge(:id => id)), :status => 201) + stub_json_request(:post, %r{test_resources}, json(test_resource: attr.merge(id: id)), status: 201) end it "should be true without an id" do @@ -187,9 +185,9 @@ context "has" do before(:each) do ZendeskAPI::TestResource.associations.clear - ZendeskAPI::TestResource.has :child, :class => ZendeskAPI::TestResource::TestChild + ZendeskAPI::TestResource.has :child, class: ZendeskAPI::TestResource::TestChild stub_json_request(:put, %r{test_resources}) - subject.child = { :id => 2 } + subject.child = {id: 2} end it "should call save on the association" do @@ -213,10 +211,10 @@ context "has_many" do before(:each) do ZendeskAPI::TestResource.associations.clear - ZendeskAPI::TestResource.has_many :children, :class => ZendeskAPI::TestResource::TestChild + ZendeskAPI::TestResource.has_many :children, class: ZendeskAPI::TestResource::TestChild stub_json_request(:put, %r{test_resources}) - stub_json_request(:get, %r{children}, json(:test_children => [])) + stub_json_request(:get, %r{children}, json(test_children: [])) end it "should reset children_ids on save" do @@ -235,21 +233,21 @@ end it "should save the associated objects when it is new" do - subject.children = [{ :foo => "bar" }] + subject.children = [{foo: "bar"}] expect(subject.children.first).to receive(:save) subject.save expect(subject.instance_variable_get(:@children)).to be_nil end it "should not save the associated objects when it is set via full hash" do - subject.children = [{ :id => 1, :foo => "bar" }] + subject.children = [{id: 1, foo: "bar"}] expect(subject.children.first).to_not receive(:save) subject.save expect(subject.instance_variable_get(:@children)).to be_nil end it "should save the associated objects when it is changes" do - subject.children = [{ :id => 1 }] + subject.children = [{id: 1}] subject.children.first.foo = "bar" expect(subject.children.first).to receive(:save) subject.save @@ -270,9 +268,9 @@ def to_param context "true" do before(:each) do - ZendeskAPI::TestResource.has :nil, :class => ZendeskAPI::NilResource, :inline => true + ZendeskAPI::TestResource.has :nil, class: ZendeskAPI::NilResource, inline: true - subject.nil = { :abc => :def } + subject.nil = {abc: :def} end it "should save param data" do @@ -291,8 +289,8 @@ def to_param context "create" do before(:each) do - ZendeskAPI::TestResource.has :nil, :class => ZendeskAPI::NilResource, :inline => :create - subject.nil = { :abc => :def } + ZendeskAPI::TestResource.has :nil, class: ZendeskAPI::NilResource, inline: :create + subject.nil = {abc: :def} end context "with a new record" do @@ -336,7 +334,7 @@ def to_param end context "instance method" do - subject { ZendeskAPI::TestResource.new(client, :id => 1) } + subject { ZendeskAPI::TestResource.new(client, id: 1) } it "throws an argumenterror without a :verb" do expect { subject.send(method) }.to raise_error(ArgumentError) @@ -344,51 +342,51 @@ def to_param context "with an array response" do before(:each) do - stub_json_request(:put, %r{test_resources/1/#{method}}, json(:test_resources => [{ :id => 1, :method => method }])) + stub_json_request(:put, %r{test_resources/1/#{method}}, json(test_resources: [{id: 1, method: method}])) end it "should return true" do - expect(subject.send(method, :verb => :put)).to be(true) + expect(subject.send(method, verb: :put)).to be(true) end it "should update the attributes if they exist" do - subject.send(method, :verb => :put) + subject.send(method, verb: :put) expect(subject[:method]).to eq(method) end end context "with a resource response" do before(:each) do - stub_json_request(:put, %r{test_resources/1/#{method}}, json(:test_resource => { :id => 1, :method => method })) + stub_json_request(:put, %r{test_resources/1/#{method}}, json(test_resource: {id: 1, method: method})) end it "should return true" do - expect(subject.send(method, :verb => :put)).to be(true) + expect(subject.send(method, verb: :put)).to be(true) end it "should update the attributes if they exist" do - subject.send(method, :verb => :put) + subject.send(method, verb: :put) expect(subject[:method]).to eq(method) end end context "with client error" do before(:each) do - stub_request(:put, %r{test_resources/1/#{method}}).to_return(:status => 500) + stub_request(:put, %r{test_resources/1/#{method}}).to_return(status: 500) end it "doesn't raise without bang" do - silence_logger { expect(subject.send(method.to_s, :verb => :put)).to be(false) } + silence_logger { expect(subject.send(method.to_s, verb: :put)).to be(false) } end it "raises with bang" do - expect { silence_logger { subject.send("#{method}!", :verb => :put) } }.to raise_error(ZendeskAPI::Error::ClientError) + expect { silence_logger { subject.send("#{method}!", verb: :put) } }.to raise_error(ZendeskAPI::Error::ClientError) end end end end - %w{put post delete}.each do |verb| + %w[put post delete].each do |verb| context "on #{verb}" do let(:method) { "test_#{verb}_method" } before(:each) do @@ -404,11 +402,11 @@ def to_param end context "instance method" do - subject { ZendeskAPI::TestResource.new(client, :id => 1) } + subject { ZendeskAPI::TestResource.new(client, id: 1) } context "with an array response" do before(:each) do - stub_json_request(verb.to_sym, %r{test_resources/1/#{method}}, json(:test_resources => [{ :id => 1, :method => method }])) + stub_json_request(verb.to_sym, %r{test_resources/1/#{method}}, json(test_resources: [{id: 1, method: method}])) end it "should return true" do @@ -423,7 +421,7 @@ def to_param context "with a resource response" do before(:each) do - stub_json_request(verb.to_sym, %r{test_resources/1/#{method}}, json(:test_resource => { :id => 1, :method => method })) + stub_json_request(verb.to_sym, %r{test_resources/1/#{method}}, json(test_resource: {id: 1, method: method})) end it "should return true" do @@ -438,7 +436,7 @@ def to_param context "with client error" do before(:each) do - stub_request(verb.to_sym, %r{test_resources/1/#{method}}).to_return(:status => 500) + stub_request(verb.to_sym, %r{test_resources/1/#{method}}).to_return(status: 500) end it "doesn't raise without bang" do @@ -460,12 +458,12 @@ def to_param else "#:bar}>" end - expect(ZendeskAPI::User.new(client, :foo => :bar).inspect).to eq(expected_user_representation) + expect(ZendeskAPI::User.new(client, foo: :bar).inspect).to eq(expected_user_representation) end end context "#to_json" do - subject { ZendeskAPI::TestResource.new(client, :id => 1) } + subject { ZendeskAPI::TestResource.new(client, id: 1) } it "should call #to_json on @attributes" do expect(subject.attributes).to receive(:to_json) @@ -488,27 +486,27 @@ def to_param end it "is different when id is different" do - expect(ZendeskAPI::TestResource.new(client, :id => 2)).to_not eq(ZendeskAPI::TestResource.new(client, :id => 1)) + expect(ZendeskAPI::TestResource.new(client, id: 2)).to_not eq(ZendeskAPI::TestResource.new(client, id: 1)) end it "is same when class is Data" do - expect(ZendeskAPI::TestResource.new(client, :id => 2)).to eq(ZendeskAPI::TestResource::TestChild.new(client, :id => 2)) + expect(ZendeskAPI::TestResource.new(client, id: 2)).to eq(ZendeskAPI::TestResource::TestChild.new(client, id: 2)) end it "is same when class is Integer" do - expect(ZendeskAPI::TestResource.new(client, :id => 2)).to eq(2) + expect(ZendeskAPI::TestResource.new(client, id: 2)).to eq(2) end it "is different when class is Integer" do - expect(ZendeskAPI::TestResource.new(client, :id => 2)).to_not eq(3) + expect(ZendeskAPI::TestResource.new(client, id: 2)).to_not eq(3) end it "is different when other is no resource" do - expect(ZendeskAPI::TestResource.new(client, :id => 2)).to_not eq(nil) + expect(ZendeskAPI::TestResource.new(client, id: 2)).to_not eq(nil) end it "warns about weird comparissons" do - object = ZendeskAPI::TestResource.new(client, :id => 2) + object = ZendeskAPI::TestResource.new(client, id: 2) expect(object).to receive(:warn) expect(object).to_not eq("xxx") end @@ -533,13 +531,13 @@ def to_param end it "should always PUT" do - ZendeskAPI::SingularTestResource.update(client, :test => :test) + ZendeskAPI::SingularTestResource.update(client, test: :test) end end end context "Ticket#assignee" do - subject { ZendeskAPI::Ticket.new(client, :id => 1, :assignee_id => nil) } + subject { ZendeskAPI::Ticket.new(client, id: 1, assignee_id: nil) } it "should not try and make a request" do expect(subject.assignee).to be_nil @@ -553,19 +551,19 @@ def to_param end it "fails to build with nil (e.g. empty response from server)" do - expect{ + expect { ZendeskAPI::TestResource.new(client, nil) }.to raise_error(/Expected a Hash/i) end end context "#create_or_update!" do - let(:params) { { :email => "hello@example.local", :test => :hello } } + let(:params) { {email: "hello@example.local", test: :hello} } subject { ZendeskAPI::CreateOrUpdateTestResource } before :each do - stub_json_request(:post, %r{create_or_update_test_resources/create_or_update}, json(:create_or_update_test_resource => { :param => "abc" })) + stub_json_request(:post, %r{create_or_update_test_resources/create_or_update}, json(create_or_update_test_resource: {param: "abc"})) end it "should return instance of resource" do @@ -574,7 +572,7 @@ def to_param context "with client error" do before(:each) do - stub_request(:post, %r{create_or_update_test_resources/create_or_update}).to_return(:status => 500) + stub_request(:post, %r{create_or_update_test_resources/create_or_update}).to_return(status: 500) end it "should raise" do diff --git a/spec/core/resources/automation_spec.rb b/spec/core/resources/automation_spec.rb index 7c7c8e4d..9e26568e 100644 --- a/spec/core/resources/automation_spec.rb +++ b/spec/core/resources/automation_spec.rb @@ -1,14 +1,12 @@ -require 'core/spec_helper' - describe ZendeskAPI::Automation do def valid_attributes { - :title => "my test automation", - :conditions => { - :any => [{ :field => "assignee_id", :operator => "is", :value => 1 }], - :all => [{ :field => "status", :operator => "is", :value => "open" }] + title: "my test automation", + conditions: { + any: [{field: "assignee_id", operator: "is", value: 1}], + all: [{field: "status", operator: "is", value: "open"}] }, - :actions => [{ :field => "priority", :value => "urgent" }] + actions: [{field: "priority", value: "urgent"}] } end @@ -19,8 +17,8 @@ def valid_attributes describe "#all_conditions=" do it "should assign new values to all conditions" do new_conditions = [ - { "field" => "type", "operator" => "is", "value" => "question" }, - { "field" => "status", "operator" => "less_than", "value" => "solved" } + {"field" => "type", "operator" => "is", "value" => "question"}, + {"field" => "status", "operator" => "less_than", "value" => "solved"} ] subject.all_conditions = new_conditions @@ -31,8 +29,8 @@ def valid_attributes describe "#any_conditions=" do it "should assign new values to any conditions" do new_conditions = [ - { "field" => "type", "operator" => "is", "value" => "question" }, - { "field" => "status", "operator" => "less_than", "value" => "solved" } + {"field" => "type", "operator" => "is", "value" => "question"}, + {"field" => "status", "operator" => "less_than", "value" => "solved"} ] subject.any_conditions = new_conditions @@ -42,7 +40,7 @@ def valid_attributes describe "#add_all_condition" do it "should add a condition to all condition" do - new_condition = { :field => "type", :operator => "is", :value => "problem" } + new_condition = {field: "type", operator: "is", value: "problem"} existing_conditions = subject.conditions[:all] expect(existing_conditions).not_to include(new_condition) @@ -55,7 +53,7 @@ def valid_attributes describe "#add_any_condition" do it "should add a condition to any condition" do - new_condition = { :field => "type", :operator => "is", :value => "task" } + new_condition = {field: "type", operator: "is", value: "task"} existing_conditions = subject.conditions[:any] expect(existing_conditions).not_to include(new_condition) @@ -68,7 +66,7 @@ def valid_attributes describe "#add_action" do it "should add an action to the current actions" do - new_action = { :field => "status", :value => "solved" } + new_action = {field: "status", value: "solved"} existing_actions = subject.actions expect(existing_actions).not_to include(new_action) diff --git a/spec/core/resources/cbp_spec_helper.rb b/spec/core/resources/cbp_spec_helper.rb index c47d6cbe..f2c03c9c 100644 --- a/spec/core/resources/cbp_spec_helper.rb +++ b/spec/core/resources/cbp_spec_helper.rb @@ -1,4 +1,4 @@ -shared_examples 'an endpoint that supports CBP' do +shared_examples "an endpoint that supports CBP" do let(:collection_fetched) do VCR.use_cassette("cbp_#{described_class}_collection_fetch") do collection.fetch @@ -9,11 +9,11 @@ let(:response_body) { collection_fetched.response.body } let(:collection_fetched_results) { collection_fetched.to_a } - it 'returns a CBP response with all the correct keys' do - expect(response_body).to have_key('meta') - expect(response_body).to have_key('links') - expect(response_body['meta'].keys).to match_array(%w[has_more after_cursor before_cursor]) - expect(response_body['links'].keys).to match_array(%w[prev next]) + it "returns a CBP response with all the correct keys" do + expect(response_body).to have_key("meta") + expect(response_body).to have_key("links") + expect(response_body["meta"].keys).to match_array(%w[has_more after_cursor before_cursor]) + expect(response_body["links"].keys).to match_array(%w[prev next]) end it "returns a list of #{described_class} objects" do diff --git a/spec/core/resources/macro_spec.rb b/spec/core/resources/macro_spec.rb index eae026aa..50209edf 100644 --- a/spec/core/resources/macro_spec.rb +++ b/spec/core/resources/macro_spec.rb @@ -1,10 +1,8 @@ -require 'core/spec_helper' - describe ZendeskAPI::Macro do def valid_attributes { - :title => "my test macro", - :actions => [{ :field => "priority", :value => "urgent" }] + title: "my test macro", + actions: [{field: "priority", value: "urgent"}] } end @@ -14,7 +12,7 @@ def valid_attributes describe "#add_action" do it "should add an action to the current actions" do - new_action = { :field => "status", :value => "solved" } + new_action = {field: "status", value: "solved"} existing_actions = subject.actions expect(existing_actions).not_to include(new_action) diff --git a/spec/core/resources/trigger_spec.rb b/spec/core/resources/trigger_spec.rb index 02002732..6fc6a642 100644 --- a/spec/core/resources/trigger_spec.rb +++ b/spec/core/resources/trigger_spec.rb @@ -1,12 +1,10 @@ -require 'core/spec_helper' - describe ZendeskAPI::Trigger do def valid_attributes { - :title => "my test trigger", - :conditions => { - :any => [{ :field => "assignee_id", :operator => "is", :value => 1 }], - :all => [{ :field => "status", :operator => "is", :value => "open" }] + title: "my test trigger", + conditions: { + any: [{field: "assignee_id", operator: "is", value: 1}], + all: [{field: "status", operator: "is", value: "open"}] } } end @@ -18,8 +16,8 @@ def valid_attributes describe "#all_conditions=" do it "should assign new values to all conditions" do new_conditions = [ - { "field" => "type", "operator" => "is", "value" => "question" }, - { "field" => "status", "operator" => "less_than", "value" => "solved" } + {"field" => "type", "operator" => "is", "value" => "question"}, + {"field" => "status", "operator" => "less_than", "value" => "solved"} ] subject.all_conditions = new_conditions @@ -30,8 +28,8 @@ def valid_attributes describe "#any_conditions=" do it "should assign new values to any conditions" do new_conditions = [ - { "field" => "type", "operator" => "is", "value" => "question" }, - { "field" => "status", "operator" => "less_than", "value" => "solved" } + {"field" => "type", "operator" => "is", "value" => "question"}, + {"field" => "status", "operator" => "less_than", "value" => "solved"} ] subject.any_conditions = new_conditions @@ -41,7 +39,7 @@ def valid_attributes describe "#add_all_condition" do it "should add a condition to all condition" do - new_condition = { :field => "type", :operator => "is", :value => "problem" } + new_condition = {field: "type", operator: "is", value: "problem"} existing_conditions = subject.conditions[:all] expect(existing_conditions).not_to include(new_condition) @@ -54,7 +52,7 @@ def valid_attributes describe "#add_any_condition" do it "should add a condition to any condition" do - new_condition = { :field => "type", :operator => "is", :value => "task" } + new_condition = {field: "type", operator: "is", value: "task"} existing_conditions = subject.conditions[:any] expect(existing_conditions).not_to include(new_condition) diff --git a/spec/core/resources/view_spec.rb b/spec/core/resources/view_spec.rb index 8fd1bdf7..a31d903d 100644 --- a/spec/core/resources/view_spec.rb +++ b/spec/core/resources/view_spec.rb @@ -1,15 +1,13 @@ -require 'core/spec_helper' - describe ZendeskAPI::View do def valid_attributes { - :title => "my test view", - :conditions => { - :any => [{ :field => "assignee_id", :operator => "is", :value => 1 }], - :all => [{ :field => "status", :operator => "is", :value => "open" }] + title: "my test view", + conditions: { + any: [{field: "assignee_id", operator: "is", value: 1}], + all: [{field: "status", operator: "is", value: "open"}] }, - :execution => { - :columns => [:id => "status", :title => "Status"] + execution: { + columns: [id: "status", title: "Status"] } } end @@ -27,7 +25,7 @@ def valid_attributes end it "should set columns on output" do - new_columns = %w(type priority) + new_columns = %w[type priority] subject.columns = new_columns expect(subject.output["columns"]).to eq(new_columns) @@ -48,8 +46,8 @@ def valid_attributes describe "#all_conditions=" do it "should assign new values to all conditions" do new_conditions = [ - { "field" => "type", "operator" => "is", "value" => "question" }, - { "field" => "status", "operator" => "less_than", "value" => "solved" } + {"field" => "type", "operator" => "is", "value" => "question"}, + {"field" => "status", "operator" => "less_than", "value" => "solved"} ] subject.all_conditions = new_conditions @@ -60,8 +58,8 @@ def valid_attributes describe "#any_conditions=" do it "should assign new values to any conditions" do new_conditions = [ - { "field" => "type", "operator" => "is", "value" => "question" }, - { "field" => "status", "operator" => "less_than", "value" => "solved" } + {"field" => "type", "operator" => "is", "value" => "question"}, + {"field" => "status", "operator" => "less_than", "value" => "solved"} ] subject.any_conditions = new_conditions @@ -71,7 +69,7 @@ def valid_attributes describe "#add_all_condition" do it "should add a condition to all condition" do - new_condition = { :field => "type", :operator => "is", :value => "problem" } + new_condition = {field: "type", operator: "is", value: "problem"} existing_conditions = subject.conditions[:all] expect(existing_conditions).not_to include(new_condition) @@ -84,7 +82,7 @@ def valid_attributes describe "#add_any_condition" do it "should add a condition to any condition" do - new_condition = { :field => "type", :operator => "is", :value => "task" } + new_condition = {field: "type", operator: "is", value: "task"} existing_conditions = subject.conditions[:any] expect(existing_conditions).not_to include(new_condition) diff --git a/spec/core/search_export_spec.rb b/spec/core/search_export_spec.rb index 1c9d2c4a..17362d23 100644 --- a/spec/core/search_export_spec.rb +++ b/spec/core/search_export_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - describe ZendeskAPI::SearchExport do describe ".new" do context "when given an existing class" do diff --git a/spec/core/search_spec.rb b/spec/core/search_spec.rb index 93e63460..521d4646 100644 --- a/spec/core/search_spec.rb +++ b/spec/core/search_spec.rb @@ -1,16 +1,14 @@ -require 'core/spec_helper' - describe ZendeskAPI::Search do context ".new" do context "when given an existing class" do it "should return the correct class" do - expect(ZendeskAPI::Search.new(nil, { "result_type" => "user" })).to be_instance_of(ZendeskAPI::User) + expect(ZendeskAPI::Search.new(nil, {"result_type" => "user"})).to be_instance_of(ZendeskAPI::User) end end context "when given a nonexistent class" do it "should return an object of the type Search::Result" do - expect(ZendeskAPI::Search.new(nil, { "result_type" => "blah" })).to be_instance_of(ZendeskAPI::Search::Result) + expect(ZendeskAPI::Search.new(nil, {"result_type" => "blah"})).to be_instance_of(ZendeskAPI::Search::Result) end end diff --git a/spec/core/spec_helper.rb b/spec/core/spec_helper.rb index 02c910f0..213d65b9 100644 --- a/spec/core/spec_helper.rb +++ b/spec/core/spec_helper.rb @@ -1,14 +1,13 @@ -$:.unshift(File.join(File.dirname(__FILE__), "macros")) +ENV["TZ"] = "CET" # something that is not local and not utc so we find all the bugs -ENV['TZ'] = 'CET' # something that is not local and not utc so we find all the bugs - -require 'zendesk_api' -require 'vcr' -require 'logger' -require 'stringio' +require "zendesk_api" +require "vcr" +require "logger" +require "stringio" +require "webmock/rspec" begin - require 'byebug' + require "byebug" rescue LoadError puts "WARN: #{$ERROR_INFO.message} Continuing..." end @@ -19,15 +18,15 @@ def encoding_aware? end end -require File.join(File.dirname(__FILE__), '..', 'macros', 'resource_macros') -require File.join(File.dirname(__FILE__), '..', 'fixtures', 'zendesk') -require File.join(File.dirname(__FILE__), '..', 'fixtures', 'test_resources') +require_relative "../macros/resource_macros" +require_relative "../fixtures/zendesk" +require_relative "../fixtures/test_resources" $credentials_warning = false # tests fail when this is included in a Module (someone else also defines client) def client - credentials = File.join(File.dirname(__FILE__), '..', 'fixtures', 'credentials.yml') + credentials = File.join(__dir__, "..", "fixtures", "credentials.yml") @client ||= begin client = ZendeskAPI::Client.new do |config| if File.exist?(credentials) @@ -48,7 +47,7 @@ def client def options super.tap do |options| options[:headers].merge!( - :authorization => "Basic #{Base64.urlsafe_encode64(authorization)}" + authorization: "Basic #{Base64.urlsafe_encode64(authorization)}" ) end end @@ -95,7 +94,7 @@ def options end def random_string(length = 10) - ('a'..'z').to_a.shuffle.take(length).join + ("a".."z").to_a.shuffle.take(length).join end module TestHelper @@ -108,7 +107,7 @@ def silence_logger end def silence_stderr - $stderr = File.new(File::NULL, 'w') + $stderr = File.new(File::NULL, "w") yield ensure $stderr = STDERR @@ -120,7 +119,7 @@ def json(body = {}) def stub_json_request(verb, path_matcher, body = json, options = {}) stub_request(verb, path_matcher).to_return(Hashie::Mash.new( - :body => body, :headers => { :content_type => "application/json", :content_length => body.size } + body: body, headers: {content_type: "application/json", content_length: body.size} ).deep_merge(options)) end end @@ -128,7 +127,7 @@ def stub_json_request(verb, path_matcher, body = json, options = {}) RSpec.configure do |c| c.before(:each) do ZendeskAPI::TestResource.associations.clear - ZendeskAPI::TestResource.has_many :children, :class => ZendeskAPI::TestResource::TestChild + ZendeskAPI::TestResource.has_many :children, class: ZendeskAPI::TestResource::TestChild end c.before(:each) do @@ -156,8 +155,8 @@ def stub_json_request(verb, path_matcher, body = json, options = {}) end VCR.configure do |c| - c.cassette_library_dir = File.join(File.dirname(__FILE__), '..', 'fixtures', 'cassettes') - c.default_cassette_options = { :record => :new_episodes, :decode_compressed_response => true, :serialize_with => :json, :preserve_exact_body_bytes => true } + c.cassette_library_dir = File.join(__dir__, "..", "fixtures", "cassettes") + c.default_cassette_options = {record: :new_episodes, decode_compressed_response: true, serialize_with: :json, preserve_exact_body_bytes: true} c.hook_into :webmock c.configure_rspec_metadata! @@ -165,5 +164,3 @@ def stub_json_request(verb, path_matcher, body = json, options = {}) # In development, this helps debugging. c.allow_http_connections_when_no_cassette = true end - -include WebMock::API diff --git a/spec/core/trackie_spec.rb b/spec/core/trackie_spec.rb index 210753a1..255a52aa 100644 --- a/spec/core/trackie_spec.rb +++ b/spec/core/trackie_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - describe ZendeskAPI::Trackie do subject { ZendeskAPI::Trackie.new } before(:each) { subject.clear_changes } @@ -73,23 +71,22 @@ end end -=begin TODO - context "nested arrays" do - before(:each) do - subject[:key] = [] - subject.clear_changes - subject[:key] << :test - end - - it "should include changes from nested array" do - expect(subject.changes[:key]).to eq([:test]) - end - - specify "subject should be changed" do - expect(subject.changed?).to be(true) - end - end -=end + # TODO + # context "nested arrays" do + # before(:each) do + # subject[:key] = [] + # subject.clear_changes + # subject[:key] << :test + # end + # + # it "should include changes from nested array" do + # expect(subject.changes[:key]).to eq([:test]) + # end + # + # specify "subject should be changed" do + # expect(subject.changed?).to be(true) + # end + # end context "nested hashes in arrays" do before(:each) do diff --git a/spec/fixtures/zendesk.rb b/spec/fixtures/zendesk.rb index 58a6316e..4db2b749 100644 --- a/spec/fixtures/zendesk.rb +++ b/spec/fixtures/zendesk.rb @@ -5,8 +5,8 @@ def user end def current_user - VCR.use_cassette('current_user') do - @current_user ||= client.users.find(:id => 'me') + VCR.use_cassette("current_user") do + @current_user ||= client.users.find(id: "me") end end @@ -20,77 +20,77 @@ def find_or_create_user(role) client.users.search(query: "email:#{email}").first || client.users.create( - :name => "Test Valid with role #{role}", - :verified => true, - :email => email, - :role => role + name: "Test Valid with role #{role}", + verified: true, + email: email, + role: role ) end end def topic - VCR.use_cassette('valid_topic') do + VCR.use_cassette("valid_topic") do @topic ||= client.topics.fetch.find { |t| t.name == "Test Topic" } @topic ||= client.topics.create( - :name => "Test Topic", - :description => "This is the body of a topic." + name: "Test Topic", + description: "This is the body of a topic." ) end end def category - VCR.use_cassette('valid_category') do + VCR.use_cassette("valid_category") do @category ||= client.categories.first - @category ||= client.categories.create(:name => "Test Category") + @category ||= client.categories.create(name: "Test Category") end end def section - VCR.use_cassette('valid_section') do + VCR.use_cassette("valid_section") do @section ||= client.sections.first end end def article - VCR.use_cassette('valid_article') do + VCR.use_cassette("valid_article") do @article ||= client.articles.first end end def ticket - VCR.use_cassette('valid_ticket') do - @ticket ||= client.tickets.detect { |t| t.status != 'closed' } + VCR.use_cassette("valid_ticket") do + @ticket ||= client.tickets.detect { |t| t.status != "closed" } @ticket ||= client.tickets.create( - :subject => "Test Ticket", - :description => "This is a test of the emergency alert system.", - :requester_id => user.id + subject: "Test Ticket", + description: "This is a test of the emergency alert system.", + requester_id: user.id ) end end def suspended_ticket - VCR.use_cassette('valid_suspended_ticket') do + VCR.use_cassette("valid_suspended_ticket") do @suspended_ticket ||= client.suspended_tickets.first @suspended_ticket ||= begin client.anonymous_requests.create( - :subject => "Test Ticket", - :comment => { :value => "Help! I need somebody." }, - :requester => { :email => "zendesk-api-client-ruby-anonymous-#{client.config.username}", :name => 'Anonymous User' } + subject: "Test Ticket", + comment: {value: "Help! I need somebody."}, + requester: {email: "zendesk-api-client-ruby-anonymous-#{client.config.username}", name: "Anonymous User"} ) - client.suspended_tickets(:reload => true).first + client.suspended_tickets(reload: true).first end end end def group - VCR.use_cassette('valid_group') do + VCR.use_cassette("valid_group") do @ticket ||= client.groups.detect { |g| !g.default } - @ticket ||= client.groups.create(:name => "Test Group") + @ticket ||= client.groups.create(name: "Test Group") end end def organization - VCR.use_cassette('valid_organization') do + VCR.use_cassette("valid_organization") do current_user.organization # ... or, if you can't work it out locally: # @organization ||= current_user.organization || client.organizations.fetch!.last @@ -98,7 +98,7 @@ def organization end def brand - VCR.use_cassette('valid_brand') do + VCR.use_cassette("valid_brand") do @brand ||= client.brands.detect do |brand| client.config.url.start_with?(brand.brand_url) end @@ -106,9 +106,9 @@ def brand end def dynamic_content_item - VCR.use_cassette('valid_dynamic_content') do + VCR.use_cassette("valid_dynamic_content") do @item ||= client.dynamic_content.items.first - @item ||= client.dynamic_content.items.create!(:name => 'Test Item', :content => 'Testing', :default_locale_id => 1) + @item ||= client.dynamic_content.items.create!(name: "Test Item", content: "Testing", default_locale_id: 1) end end end diff --git a/spec/live/app_installation_spec.rb b/spec/live/app_installation_spec.rb index 3d405316..6f16bcf0 100644 --- a/spec/live/app_installation_spec.rb +++ b/spec/live/app_installation_spec.rb @@ -1,12 +1,10 @@ -require 'core/spec_helper' - describe ZendeskAPI::AppInstallation do it "should work" do upload = VCR.use_cassette("app_installations_upload_create") do - ZendeskAPI::App::Upload.new(client, :id => "spec/fixtures/sample_app.zip").tap(&:save!) + ZendeskAPI::App::Upload.new(client, id: "spec/fixtures/sample_app.zip").tap(&:save!) end - attributes = { :upload_id => upload.id, :name => "My App", :short_description => "Testing" } + attributes = {upload_id: upload.id, name: "My App", short_description: "Testing"} app = ZendeskAPI::App.new(client, attributes) @@ -15,7 +13,7 @@ body = {} VCR.use_cassette("app_installations_create_job_status") do - until %w{failed completed}.include?(body["status"]) + until %w[failed completed].include?(body["status"]) response = client.connection.get(app.response.headers["Location"]) body = response.body @@ -30,9 +28,9 @@ app.id = body["app_id"] attributes = { - :app_id => app.id, - :settings => { - :name => "My App" + app_id: app.id, + settings: { + name: "My App" } } @@ -42,7 +40,7 @@ installations = client.app.installations VCR.use_cassette("app_install_fetch") { installations.fetch! } - VCR.use_cassette("app_install_find") { client.app.installations.find!(:id => install.id) } + VCR.use_cassette("app_install_find") { client.app.installations.find!(id: install.id) } expect(installations).to include(install) diff --git a/spec/live/app_spec.rb b/spec/live/app_spec.rb index 2f9459b9..917e7c8e 100644 --- a/spec/live/app_spec.rb +++ b/spec/live/app_spec.rb @@ -1,12 +1,10 @@ -require 'core/spec_helper' - describe ZendeskAPI::App do it "should work" do upload = VCR.use_cassette("app_upload_create") do - ZendeskAPI::App::Upload.new(client, :id => "spec/fixtures/sample_app.zip").tap(&:save!) + ZendeskAPI::App::Upload.new(client, id: "spec/fixtures/sample_app.zip").tap(&:save!) end - attributes = { :upload_id => upload.id, :name => "My App", :short_description => "Testing" } + attributes = {upload_id: upload.id, name: "My App", short_description: "Testing"} app = ZendeskAPI::App.new(client, attributes) @@ -22,13 +20,13 @@ expect(app.author_name).to eq("Mr. Sprinkles") - VCR.use_cassette("app_find") { client.apps.find!(:id => app.id) } + VCR.use_cassette("app_find") { client.apps.find!(id: app.id) } VCR.use_cassette("app_destroy") { app.destroy! } end it "should be able to handle the simplest creation api call" do VCR.use_cassette("app_simple_create") do - app = ZendeskAPI::App.create!(client, { :name => "Testing App Creation", :upload => "spec/fixtures/sample_app.zip" }) + app = ZendeskAPI::App.create!(client, {name: "Testing App Creation", upload: "spec/fixtures/sample_app.zip"}) body = check_job(app) @@ -41,7 +39,7 @@ def check_job(app) body = {} VCR.use_cassette("app_create_job_status") do - until %w{failed completed}.include?(body["status"]) + until %w[failed completed].include?(body["status"]) response = client.connection.get(app.response.headers["Location"]) body = response.body diff --git a/spec/live/article_spec.rb b/spec/live/article_spec.rb index 018d67f6..783a91c7 100644 --- a/spec/live/article_spec.rb +++ b/spec/live/article_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - RSpec.describe ZendeskAPI::Article, :delete_after do it "expects article to exist" do expect(article).not_to be_nil @@ -21,17 +19,17 @@ describe "creating articles within a section" do def valid_attributes - { :name => "My Article", user_segment_id: nil, permission_group_id: "9903096093850", title: "My super article" } + {name: "My Article", user_segment_id: nil, permission_group_id: "9903096093850", title: "My super article"} end let(:section_article) do - VCR.use_cassette('create_article_within_section') do + VCR.use_cassette("create_article_within_section") do section.articles.create(valid_attributes) end end after do - VCR.use_cassette('delete_article_within_section') do + VCR.use_cassette("delete_article_within_section") do section_article.destroy end end diff --git a/spec/live/audit_spec.rb b/spec/live/audit_spec.rb index 6e6f0320..fbefcf3d 100644 --- a/spec/live/audit_spec.rb +++ b/spec/live/audit_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - describe ZendeskAPI::Ticket::Audit do it_should_be_readable ticket, :audits diff --git a/spec/live/automation_spec.rb b/spec/live/automation_spec.rb index 45fdef6e..3bcbf26d 100644 --- a/spec/live/automation_spec.rb +++ b/spec/live/automation_spec.rb @@ -1,13 +1,11 @@ -require 'core/spec_helper' - describe ZendeskAPI::Automation, :delete_after do def valid_attributes { - :title => "my test automation_ruby_sdk_test", - :conditions => { - :all => [{ :field => "status", :operator => "is", :value => "open" }] + title: "my test automation_ruby_sdk_test", + conditions: { + all: [{field: "status", operator: "is", value: "open"}] }, - :actions => [{ :field => "status", :value => "solved" }] + actions: [{field: "status", value: "solved"}] } end @@ -17,7 +15,7 @@ def valid_attributes it_should_be_creatable it_should_be_updatable :conditions, { "any" => [], - "all" => [{ "field" => "status", "operator" => "is", "value" => "pending" }] + "all" => [{"field" => "status", "operator" => "is", "value" => "pending"}] } it_should_be_deletable end diff --git a/spec/live/bookmark_spec.rb b/spec/live/bookmark_spec.rb index edbad8f1..34ac3f3d 100644 --- a/spec/live/bookmark_spec.rb +++ b/spec/live/bookmark_spec.rb @@ -1,11 +1,9 @@ -require 'core/spec_helper' - describe ZendeskAPI::Bookmark, :not_findable, :delete_after do def valid_attributes - { :ticket_id => ticket.id } + {ticket_id: ticket.id} end it_should_be_creatable it_should_be_deletable - it_should_be_readable :bookmarks, :create => true + it_should_be_readable :bookmarks, create: true end diff --git a/spec/live/brand_spec.rb b/spec/live/brand_spec.rb index 15edf749..011f3853 100644 --- a/spec/live/brand_spec.rb +++ b/spec/live/brand_spec.rb @@ -1,8 +1,6 @@ -require 'core/spec_helper' - describe ZendeskAPI::Brand, :delete_after do def valid_attributes - { :name => "awesomesauce_ruby_sdk_test_brand", :subdomain => "zendeskapi#{SecureRandom.hex(3)}" } + {name: "awesomesauce_ruby_sdk_test_brand", subdomain: "zendeskapi#{SecureRandom.hex(3)}"} end it_should_be_creatable @@ -10,5 +8,5 @@ def valid_attributes it_should_be_readable :brands # Deleted brands are still findable by id, but in the index action - it_should_be_deletable :find => nil + it_should_be_deletable find: nil end diff --git a/spec/live/category_spec.rb b/spec/live/category_spec.rb index 3e8da759..9452cdf5 100644 --- a/spec/live/category_spec.rb +++ b/spec/live/category_spec.rb @@ -1,8 +1,6 @@ -require 'core/spec_helper' - describe ZendeskAPI::Category, :delete_after do def valid_attributes - { :name => "My Category" } + {name: "My Category"} end it "can have translations", :vcr do @@ -14,5 +12,5 @@ def valid_attributes it_should_be_creatable it_should_be_updatable :position, 2 it_should_be_deletable - it_should_be_readable :categories, :create => true + it_should_be_readable :categories, create: true end diff --git a/spec/live/cbp_support_spec.rb b/spec/live/cbp_support_spec.rb index 639ce544..7c304c15 100644 --- a/spec/live/cbp_support_spec.rb +++ b/spec/live/cbp_support_spec.rb @@ -1,71 +1,70 @@ -require 'core/spec_helper' -require 'core/resources/cbp_spec_helper' +require_relative "../core/resources/cbp_spec_helper" -describe 'Endpoints that support CBP' do +describe "Endpoints that support CBP" do describe ZendeskAPI::Group do - describe '/groups' do - it_behaves_like 'an endpoint that supports CBP' do + describe "/groups" do + it_behaves_like "an endpoint that supports CBP" do let(:collection) { client.groups } end end - describe '/groups/assignable' do - it_behaves_like 'an endpoint that supports CBP' do + describe "/groups/assignable" do + it_behaves_like "an endpoint that supports CBP" do let(:collection) { client.groups.assignable } end end end describe ZendeskAPI::GroupMembership do - describe '/groups/:id/memberships' do + describe "/groups/:id/memberships" do let(:one_group) { VCR.use_cassette("cbp_group_memberships_all_groups") { client.groups.fetch.last } } - it_behaves_like 'an endpoint that supports CBP' do + it_behaves_like "an endpoint that supports CBP" do let(:collection) { one_group.memberships } end end end describe ZendeskAPI::Organization do - describe '/organizations' do - it_behaves_like 'an endpoint that supports CBP' do + describe "/organizations" do + it_behaves_like "an endpoint that supports CBP" do let(:collection) { client.organizations } end end end describe ZendeskAPI::OrganizationMembership do - describe '/organizations/:id/subscriptions' do + describe "/organizations/:id/subscriptions" do let(:one_organization) { VCR.use_cassette("cbp_organization_subscriptions_all_organizations") { client.organizations.fetch.last } } - it_behaves_like 'an endpoint that supports CBP' do + it_behaves_like "an endpoint that supports CBP" do let(:collection) { one_organization.subscriptions } end end end describe ZendeskAPI::Trigger do - describe '/triggers' do - it_behaves_like 'an endpoint that supports CBP' do + describe "/triggers" do + it_behaves_like "an endpoint that supports CBP" do let(:collection) { client.triggers } end end - describe '/triggers/active' do - it_behaves_like 'an endpoint that supports CBP' do + describe "/triggers/active" do + it_behaves_like "an endpoint that supports CBP" do let(:collection) { client.triggers.active } end end end describe ZendeskAPI::TicketField do - describe '/ticket_fields' do - it_behaves_like 'an endpoint that supports CBP' do + describe "/ticket_fields" do + it_behaves_like "an endpoint that supports CBP" do let(:collection) { client.ticket_fields } end end end describe ZendeskAPI::Topic do - describe '/community/topics' do + describe "/community/topics" do let(:collection_fetched) do VCR.use_cassette("cbp_#{described_class}_collection_fetch") do client.topics.fetch @@ -76,10 +75,10 @@ let(:response_body) { collection_fetched.response.body } let(:collection_fetched_results) { collection_fetched.to_a } - it 'returns a CBP response with all the correct keys' do - expect(response_body).to have_key('meta') - expect(response_body).to have_key('links') - expect(response_body['meta'].keys).to match_array(%w[has_more after_cursor before_cursor]) + it "returns a CBP response with all the correct keys" do + expect(response_body).to have_key("meta") + expect(response_body).to have_key("links") + expect(response_body["meta"].keys).to match_array(%w[has_more after_cursor before_cursor]) # expect(response_body['links'].keys).to match_array(%w[prev next]) this implementation omits prev and next keys # instead of giving them a nil value end @@ -91,152 +90,152 @@ end describe ZendeskAPI::View do - describe '/views' do - it_behaves_like 'an endpoint that supports CBP' do + describe "/views" do + it_behaves_like "an endpoint that supports CBP" do let(:collection) { client.views } end end end describe ZendeskAPI::Ticket do - describe '/tickets' do - it_behaves_like 'an endpoint that supports CBP' do + describe "/tickets" do + it_behaves_like "an endpoint that supports CBP" do let(:collection) { client.tickets } end end - describe '/organizations/:id/tickets' do + describe "/organizations/:id/tickets" do let(:organization) do VCR.use_cassette("cbp_#{described_class}_organization_fetch") do client.organizations.fetch.first end end - it_behaves_like 'an endpoint that supports CBP' do + it_behaves_like "an endpoint that supports CBP" do let(:collection) { organization.tickets } end end - describe '/users/:id/tickets/requested' do + describe "/users/:id/tickets/requested" do let(:user) do VCR.use_cassette("cbp_#{described_class}_user_fetch") do client.users.fetch.first end end - it_behaves_like 'an endpoint that supports CBP' do + it_behaves_like "an endpoint that supports CBP" do let(:collection) { user.requested_tickets } end end end describe ZendeskAPI::Ticket::Audit do - describe '/tickets/:id/audits' do + describe "/tickets/:id/audits" do let(:ticket) do VCR.use_cassette("cbp_#{described_class}_ticket_fetch") do client.tickets.fetch.first end end - it_behaves_like 'an endpoint that supports CBP' do + it_behaves_like "an endpoint that supports CBP" do let(:collection) { ticket.audits } end end end describe ZendeskAPI::TicketMetric do - describe '/ticket_metrics' do - it_behaves_like 'an endpoint that supports CBP' do + describe "/ticket_metrics" do + it_behaves_like "an endpoint that supports CBP" do let(:collection) { client.ticket_metrics } end end end describe ZendeskAPI::Tag do - describe '/tags' do - it_behaves_like 'an endpoint that supports CBP' do + describe "/tags" do + it_behaves_like "an endpoint that supports CBP" do let(:collection) { client.tags } end end end describe ZendeskAPI::SuspendedTicket do - describe '/suspended_tickets' do - it_behaves_like 'an endpoint that supports CBP' do + describe "/suspended_tickets" do + it_behaves_like "an endpoint that supports CBP" do let(:collection) { client.suspended_tickets } end end end describe ZendeskAPI::Activity do - describe '/activities' do - it_behaves_like 'an endpoint that supports CBP' do + describe "/activities" do + it_behaves_like "an endpoint that supports CBP" do let(:collection) { client.activities } end end end describe ZendeskAPI::Automation do - describe '/automations' do - it_behaves_like 'an endpoint that supports CBP' do + describe "/automations" do + it_behaves_like "an endpoint that supports CBP" do let(:collection) { client.automations } end end end describe ZendeskAPI::DeletedTicket do - describe '/deleted_tickets' do - it_behaves_like 'an endpoint that supports CBP' do + describe "/deleted_tickets" do + it_behaves_like "an endpoint that supports CBP" do let(:collection) { client.deleted_tickets } end end end describe ZendeskAPI::Macro do - describe '/macros' do - it_behaves_like 'an endpoint that supports CBP' do + describe "/macros" do + it_behaves_like "an endpoint that supports CBP" do let(:collection) { client.macros } end end end describe ZendeskAPI::OauthClient do - describe '/oauth/clients' do - it_behaves_like 'an endpoint that supports CBP' do + describe "/oauth/clients" do + it_behaves_like "an endpoint that supports CBP" do let(:collection) { client.oauth_clients } end end end describe ZendeskAPI::Brand do - describe '/brands' do - it_behaves_like 'an endpoint that supports CBP' do + describe "/brands" do + it_behaves_like "an endpoint that supports CBP" do let(:collection) { client.brands } end end end describe ZendeskAPI::User do - describe '/users' do - it_behaves_like 'an endpoint that supports CBP' do + describe "/users" do + it_behaves_like "an endpoint that supports CBP" do let(:collection) { client.users } end end - describe '/organizations/:id/users' do + describe "/organizations/:id/users" do let(:organization) do VCR.use_cassette("cbp_#{described_class}_organization_fetch") do client.organizations.fetch.first end end - it_behaves_like 'an endpoint that supports CBP' do + it_behaves_like "an endpoint that supports CBP" do let(:collection) { organization.users } end end end describe ZendeskAPI::AgentAvailability do - describe '/agent_availabilities' do + describe "/agent_availabilities" do let(:collection_fetched) do VCR.use_cassette("cbp_#{described_class}_collection") do client.agent_availabilities.fetch @@ -246,13 +245,13 @@ let(:response_body) { collection_fetched.response.body } let(:collection_fetched_results) { collection_fetched.to_a } - it 'returns a CBP response with all the correct keys' do - expect(response_body).to have_key('meta') - expect(response_body).to have_key('links') - expect(response_body['meta'].keys).to include('has_more') + it "returns a CBP response with all the correct keys" do + expect(response_body).to have_key("meta") + expect(response_body).to have_key("links") + expect(response_body["meta"].keys).to include("has_more") end - it 'returns a list of AgentAvailability objects' do + it "returns a list of AgentAvailability objects" do expect(collection_fetched_results).to all(be_a(described_class)) end end diff --git a/spec/live/collection_spec.rb b/spec/live/collection_spec.rb index 7025f29e..6238eeb9 100644 --- a/spec/live/collection_spec.rb +++ b/spec/live/collection_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - describe ZendeskAPI::Collection do subject do ZendeskAPI::Collection.new(client, ZendeskAPI::TestResource) @@ -11,7 +9,7 @@ end before(:each) do - VCR.use_cassette('collection_fetch_users') do + VCR.use_cassette("collection_fetch_users") do subject.per_page(1).page(2) subject.fetch(true) end diff --git a/spec/live/custom_role_spec.rb b/spec/live/custom_role_spec.rb index 6ba703b2..b4cefce7 100644 --- a/spec/live/custom_role_spec.rb +++ b/spec/live/custom_role_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - describe ZendeskAPI::CustomRole do it_should_be_readable :custom_roles end diff --git a/spec/live/custom_status_spec.rb b/spec/live/custom_status_spec.rb index d52a2d7b..8c40a1ce 100644 --- a/spec/live/custom_status_spec.rb +++ b/spec/live/custom_status_spec.rb @@ -1,10 +1,9 @@ -require 'core/spec_helper' -require 'securerandom' +require "securerandom" describe ZendeskAPI::CustomStatus, :delete_after do def valid_attributes { - status_category: 'open', + status_category: "open", agent_label: "Agent Label #{SecureRandom.hex(6)}", end_user_label: "End User Label #{SecureRandom.hex(6)}", description: "Description #{SecureRandom.hex(6)}", @@ -15,9 +14,9 @@ def valid_attributes it_should_be_creatable it_should_be_updatable :agent_label, "ruby_sdk_test_agent_label_updated" - it_should_be_updatable :end_user_label, 'New End User Label' - it_should_be_updatable :description, 'New Description' - it_should_be_updatable :end_user_description, 'New End User Description' + it_should_be_updatable :end_user_label, "New End User Label" + it_should_be_updatable :description, "New Description" + it_should_be_updatable :end_user_description, "New End User Description" it_should_be_deletable find: [:active?, false] it_should_be_readable :custom_statuses end diff --git a/spec/live/dynamic_content/item_spec.rb b/spec/live/dynamic_content/item_spec.rb index 91f938ae..93e66be6 100644 --- a/spec/live/dynamic_content/item_spec.rb +++ b/spec/live/dynamic_content/item_spec.rb @@ -1,16 +1,14 @@ -require 'core/spec_helper' - describe ZendeskAPI::DynamicContent::Item, :delete_after do def valid_attributes { - :name => "Dynamic Content Item name Ruby SDK test", - :default_locale_id => 1, - :content => "Ruby SDK test content" + name: "Dynamic Content Item name Ruby SDK test", + default_locale_id: 1, + content: "Ruby SDK test content" } end - it_should_be_readable :dynamic_content, :items, :create => true + it_should_be_readable :dynamic_content, :items, create: true it_should_be_creatable - it_should_be_updatable :name, 'Updated Dynamic Content Item name Ruby SDK test' + it_should_be_updatable :name, "Updated Dynamic Content Item name Ruby SDK test" it_should_be_deletable end diff --git a/spec/live/dynamic_content/variant_spec.rb b/spec/live/dynamic_content/variant_spec.rb index f7fbe50e..2a282424 100644 --- a/spec/live/dynamic_content/variant_spec.rb +++ b/spec/live/dynamic_content/variant_spec.rb @@ -1,17 +1,15 @@ -require 'core/spec_helper' - describe ZendeskAPI::DynamicContent::Item::Variant, :delete_after do def valid_attributes { - :locale_id => 2, - :active => true, - :default => false, - :content => 'Ruby SDK Test Variant Content' + locale_id: 2, + active: true, + default: false, + content: "Ruby SDK Test Variant Content" } end under dynamic_content_item do - it_should_be_readable dynamic_content_item, :variants, :create => true + it_should_be_readable dynamic_content_item, :variants, create: true it_should_be_creatable it_should_be_updatable :content it_should_be_deletable diff --git a/spec/live/group_membership_spec.rb b/spec/live/group_membership_spec.rb index f64bae50..23d4b8b5 100644 --- a/spec/live/group_membership_spec.rb +++ b/spec/live/group_membership_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - describe ZendeskAPI::GroupMembership, :delete_after do before :all do VCR.use_cassette("delete_existing_group_memberships_create") do @@ -8,11 +6,11 @@ end def valid_attributes - { :group_id => group.id, :user_id => agent.id } + {group_id: group.id, user_id: agent.id} end it_should_be_creatable it_should_be_deletable it_should_be_readable :group_memberships - it_should_be_readable agent, :group_memberships, :create => true + it_should_be_readable agent, :group_memberships, create: true end diff --git a/spec/live/group_spec.rb b/spec/live/group_spec.rb index a7b56062..03dd9db4 100644 --- a/spec/live/group_spec.rb +++ b/spec/live/group_spec.rb @@ -1,13 +1,11 @@ -require 'core/spec_helper' - describe ZendeskAPI::Group, :delete_after do def valid_attributes - { :name => "My Group" } + {name: "My Group"} end it_should_be_creatable it_should_be_updatable :name - it_should_be_deletable :find => [:deleted?, true] + it_should_be_deletable find: [:deleted?, true] it_should_be_readable :groups it_should_be_readable :groups, :assignable @@ -17,7 +15,7 @@ def valid_attributes attrs = valid_attributes attrs.merge!(@default_options) if @default_options @object = described_class.create!(client, attrs) - @membership = agent.group_memberships.create(:group_id => @object.id, :user_id => agent.id) + @membership = agent.group_memberships.create(group_id: @object.id, user_id: agent.id) end end diff --git a/spec/live/identity_spec.rb b/spec/live/identity_spec.rb index 8a6fed74..a8ce3c88 100644 --- a/spec/live/identity_spec.rb +++ b/spec/live/identity_spec.rb @@ -1,14 +1,12 @@ -require 'core/spec_helper' - describe ZendeskAPI::User::Identity, :delete_after do def valid_attributes - { :type => "email", :value => "ruby_sdk_test@example.com" } + {type: "email", value: "ruby_sdk_test@example.com"} end under current_user do it_should_be_creatable it_should_be_updatable :verified, true it_should_be_deletable - it_should_be_readable current_user, :identities, :create => true + it_should_be_readable current_user, :identities, create: true end end diff --git a/spec/live/locale_spec.rb b/spec/live/locale_spec.rb index 3a2b3a84..ad52284c 100644 --- a/spec/live/locale_spec.rb +++ b/spec/live/locale_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - describe ZendeskAPI::Locale, :vcr do specify "client#current_locale" do expect(client.current_locale).to be_instance_of(described_class) diff --git a/spec/live/macro_spec.rb b/spec/live/macro_spec.rb index 0d139f03..8557064d 100644 --- a/spec/live/macro_spec.rb +++ b/spec/live/macro_spec.rb @@ -1,28 +1,26 @@ -require 'core/spec_helper' - describe ZendeskAPI::Macro, :delete_after do def valid_attributes - { :title => "my test macro", :actions => [{ :field => "status", :value => "solved" }] } + {title: "my test macro", actions: [{field: "status", value: "solved"}]} end it_should_be_readable :macros it_should_be_readable :macros, :active it_should_be_creatable - it_should_be_updatable :actions, [{ "field" => "priority", "value" => "low" }] + it_should_be_updatable :actions, [{"field" => "priority", "value" => "low"}] it_should_be_deletable describe "application", :vcr do subject { @object } before :all do - VCR.use_cassette("#{described_class.to_s}_application_create") do + VCR.use_cassette("#{described_class}_application_create") do @object = described_class.create(client, valid_attributes.merge(default_options)) end end after :all do - VCR.use_cassette("#{described_class.to_s}_application_delete") do + VCR.use_cassette("#{described_class}_application_delete") do @object.destroy end end diff --git a/spec/live/organization_field_spec.rb b/spec/live/organization_field_spec.rb index 7a8f8d01..a1d1b976 100644 --- a/spec/live/organization_field_spec.rb +++ b/spec/live/organization_field_spec.rb @@ -1,12 +1,10 @@ -require 'core/spec_helper' - describe ZendeskAPI::OrganizationField, :delete_after do def valid_attributes - { :type => "text", :title => "Age", :key => random_string(5) } + {type: "text", title: "Age", key: random_string(5)} end it_should_be_creatable it_should_be_updatable :title, "key" - it_should_be_readable :organization_fields, :create => true - it_should_be_deletable :marked_for_deletion => true + it_should_be_readable :organization_fields, create: true + it_should_be_deletable marked_for_deletion: true end diff --git a/spec/live/organization_membership_spec.rb b/spec/live/organization_membership_spec.rb index eeaeca0a..5f71eb53 100644 --- a/spec/live/organization_membership_spec.rb +++ b/spec/live/organization_membership_spec.rb @@ -1,8 +1,6 @@ -require 'core/spec_helper' - describe ZendeskAPI::OrganizationMembership, :delete_after do def valid_attributes - { :organization_id => organization.id, :user_id => user.id } + {organization_id: organization.id, user_id: user.id} end it_should_be_creatable diff --git a/spec/live/organization_spec.rb b/spec/live/organization_spec.rb index ed92194c..d51d7241 100644 --- a/spec/live/organization_spec.rb +++ b/spec/live/organization_spec.rb @@ -1,14 +1,12 @@ -require 'core/spec_helper' - describe ZendeskAPI::Organization, :delete_after do def valid_attributes - { :name => 'organization_name_ruby_sdk_test' } + {name: "organization_name_ruby_sdk_test"} end it_should_be_creatable - it_should_be_updatable :name, 'organization_name_ruby_sdk_test_updated' + it_should_be_updatable :name, "organization_name_ruby_sdk_test_updated" it_should_be_deletable - it_should_be_readable :organizations, :create => true + it_should_be_readable :organizations, create: true describe "create_or_update" do after do @@ -44,8 +42,8 @@ def valid_attributes ZendeskAPI::Organization.create_many!( client, [ - { name: "one", external_id: "101" }, - { name: "two", external_id: "102" } + {name: "one", external_id: "101"}, + {name: "two", external_id: "102"} ] ).tap do |job| job.reload! while job.status != "completed" diff --git a/spec/live/organization_subscription_spec.rb b/spec/live/organization_subscription_spec.rb index 4b2beea4..231d7791 100644 --- a/spec/live/organization_subscription_spec.rb +++ b/spec/live/organization_subscription_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - describe ZendeskAPI::OrganizationSubscription, :delete_after do before(:all) do VCR.use_cassette("enable_shared_tickets") do @@ -22,7 +20,7 @@ end def valid_attributes - { :organization_id => organization.id, :user_id => user.id } + {organization_id: organization.id, user_id: user.id} end it_should_be_creatable diff --git a/spec/live/push_notification_device_spec.rb b/spec/live/push_notification_device_spec.rb index fcbc50a5..b52c9984 100644 --- a/spec/live/push_notification_device_spec.rb +++ b/spec/live/push_notification_device_spec.rb @@ -1,11 +1,9 @@ -require 'core/spec_helper' - describe ZendeskAPI::PushNotificationDevice do describe ".destroy_many" do describe "Existing push notification devices" do it "destroys the given push notification devices" do VCR.use_cassette("push_notification_devices_destroy_many") do - ZendeskAPI::PushNotificationDevice.destroy_many(client, %w(foo bar)) + ZendeskAPI::PushNotificationDevice.destroy_many(client, %w[foo bar]) end end end diff --git a/spec/live/request_spec.rb b/spec/live/request_spec.rb index 6a54ab8b..44ae9cb3 100644 --- a/spec/live/request_spec.rb +++ b/spec/live/request_spec.rb @@ -1,15 +1,13 @@ -require 'core/spec_helper' - describe ZendeskAPI::Request do def valid_attributes { - :subject => "This is a question!", - :comment => { :value => "Haha, no." } + subject: "This is a question!", + comment: {value: "Haha, no."} } end it_should_be_creatable - it_should_be_updatable :solved, true, { :comment => { :value => 'This is solved!' } } + it_should_be_updatable :solved, true, {comment: {value: "This is solved!"}} it_should_be_readable :requests it_should_be_readable user, :requests @@ -28,11 +26,11 @@ def valid_attributes it "can comment while creating" do VCR.use_cassette("request_inline_comments") do request = ZendeskAPI::Request.new(client, valid_attributes) - request.comment = ZendeskAPI::Request::Comment.new(client, :value => "My comment") + request.comment = ZendeskAPI::Request::Comment.new(client, value: "My comment") request.save! expect(request.changes).to eq({}) # comment was set before save - expect(request.attributes[:comment]).to eq({ "value" => "My comment" }) + expect(request.attributes[:comment]).to eq({"value" => "My comment"}) end end end diff --git a/spec/live/satisfaction_rating_spec.rb b/spec/live/satisfaction_rating_spec.rb index c2bf1c91..d26acb07 100644 --- a/spec/live/satisfaction_rating_spec.rb +++ b/spec/live/satisfaction_rating_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - describe ZendeskAPI::SatisfactionRating do it_should_be_readable :satisfaction_ratings it_should_be_readable :satisfaction_ratings, :received diff --git a/spec/live/schedule_spec.rb b/spec/live/schedule_spec.rb index 814ee714..50db822e 100644 --- a/spec/live/schedule_spec.rb +++ b/spec/live/schedule_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - RSpec.describe ZendeskAPI::Schedule, :delete_after do def valid_attributes { diff --git a/spec/live/section_spec.rb b/spec/live/section_spec.rb index 479cac52..916de929 100644 --- a/spec/live/section_spec.rb +++ b/spec/live/section_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - describe ZendeskAPI::Section, :delete_after do it "expects section to exist" do expect(section).not_to be_nil @@ -13,17 +11,17 @@ describe "creating sections withing categories" do def valid_attributes - { :name => "My Section" } + {name: "My Section"} end let(:category_section) do - VCR.use_cassette('create_section_within_category') do + VCR.use_cassette("create_section_within_category") do category.sections.create(valid_attributes) end end after do - VCR.use_cassette('delete_section_within_category') do + VCR.use_cassette("delete_section_within_category") do category_section.destroy end end diff --git a/spec/live/setting_spec.rb b/spec/live/setting_spec.rb index 547e17b3..35276ac9 100644 --- a/spec/live/setting_spec.rb +++ b/spec/live/setting_spec.rb @@ -1,13 +1,11 @@ -require 'core/spec_helper' - describe ZendeskAPI::Setting do - it_should_be_readable :settings, :path => 'account/settings' + it_should_be_readable :settings, path: "account/settings" - under(user = ZendeskAPI::User.new(client, :id => 'me')) do + under(user = ZendeskAPI::User.new(client, id: "me")) do it_should_be_readable user, :settings - describe 'updating', :vcr do - it 'should be updatable' do + describe "updating", :vcr do + it "should be updatable" do settings = user.settings lotus = settings.detect { |set| set.on == "lotus" } diff --git a/spec/live/suspended_ticket_spec.rb b/spec/live/suspended_ticket_spec.rb index b9ea3cec..f3ecfeb0 100644 --- a/spec/live/suspended_ticket_spec.rb +++ b/spec/live/suspended_ticket_spec.rb @@ -1,13 +1,11 @@ -require 'core/spec_helper' - describe ZendeskAPI::SuspendedTicket do def valid_attributes { - :subject => "Test Ticket", - :comment => { :value => "Help! I need somebody." }, - :requester => { - :email => "zendesk-api-client-ruby-anonymous-#{client.config.username}", - :name => 'Anonymous User' + subject: "Test Ticket", + comment: {value: "Help! I need somebody."}, + requester: { + email: "zendesk-api-client-ruby-anonymous-#{client.config.username}", + name: "Anonymous User" } } end diff --git a/spec/live/tag_spec.rb b/spec/live/tag_spec.rb index 48196d88..6eb20ab1 100644 --- a/spec/live/tag_spec.rb +++ b/spec/live/tag_spec.rb @@ -1,50 +1,48 @@ -require 'core/spec_helper' - RSpec.describe ZendeskAPI::Tag, :vcr, :not_findable do [organization, user, ticket].each do |object| raise "Your setup is invalid, see spec/live/Readme.md" unless object under object do before do - parent.tags = %w{tag2 tag3} + parent.tags = %w[tag2 tag3] parent.tags.save! end it "can be set" do - expect(tags).to eq(%w{tag2 tag3}) + expect(tags).to eq(%w[tag2 tag3]) end it "should be removable" do - parent.tags.destroy!(:id => "tag2") + parent.tags.destroy!(id: "tag2") - expect(tags).to eq(%w{tag3}) + expect(tags).to eq(%w[tag3]) end it "shouldn't re-save destroyed tags" do parent.tags.first.destroy! parent.tags.save! - expect(tags).to eq(%w{tag3}) + expect(tags).to eq(%w[tag3]) end it "should be updatable" do - parent.tags.update!(:id => "tag4") + parent.tags.update!(id: "tag4") - expect(tags).to eq(%w{tag2 tag3 tag4}) + expect(tags).to eq(%w[tag2 tag3 tag4]) end it "should be savable" do parent.tags << "tag4" parent.tags.save! - expect(tags).to eq(%w{tag2 tag3 tag4}) + expect(tags).to eq(%w[tag2 tag3 tag4]) end it "should be modifiable" do - parent.tags.delete(ZendeskAPI::Tag.new(nil, :id => "tag2")) + parent.tags.delete(ZendeskAPI::Tag.new(nil, id: "tag2")) parent.tags.save! - expect(tags).to eq(%w{tag3}) + expect(tags).to eq(%w[tag3]) parent.tags.delete_if { |tag| tag.id == "tag3" } parent.tags.save! diff --git a/spec/live/target_spec.rb b/spec/live/target_spec.rb index 9b825de0..d73cf4f0 100644 --- a/spec/live/target_spec.rb +++ b/spec/live/target_spec.rb @@ -1,16 +1,14 @@ -require 'core/spec_helper' - describe ZendeskAPI::Target, :delete_after do def valid_attributes { - :type => "email_target", - :title => "Test Email Target", - :email => "hello@example.com", - :subject => "Test Target" + type: "email_target", + title: "Test Email Target", + email: "hello@example.com", + subject: "Test Target" } end - it_should_be_readable :targets, :create => :true + it_should_be_readable :targets, create: true it_should_be_creatable it_should_be_updatable :active, false it_should_be_deletable diff --git a/spec/live/ticket_field_spec.rb b/spec/live/ticket_field_spec.rb index 60ad611d..b3cd02e5 100644 --- a/spec/live/ticket_field_spec.rb +++ b/spec/live/ticket_field_spec.rb @@ -1,8 +1,6 @@ -require 'core/spec_helper' - describe ZendeskAPI::TicketField, :delete_after do def valid_attributes - { :type => "text", :title => "Age" } + {type: "text", title: "Age"} end it_should_be_creatable diff --git a/spec/live/ticket_form_spec.rb b/spec/live/ticket_form_spec.rb index 1f33142c..69f3820a 100644 --- a/spec/live/ticket_form_spec.rb +++ b/spec/live/ticket_form_spec.rb @@ -1,13 +1,11 @@ -require 'core/spec_helper' - describe ZendeskAPI::TicketForm, :delete_after do def valid_attributes - { :name => "Ticket Form-o", :position => 9999, :active => false } + {name: "Ticket Form-o", position: 9999, active: false} end it_should_be_creatable it_should_be_updatable :name - it_should_be_deletable :find => false # Deleted ticket forms are still returned from the show action + it_should_be_deletable find: false # Deleted ticket forms are still returned from the show action it_should_be_readable :ticket_forms # TODO: clone diff --git a/spec/live/ticket_metrics_spec.rb b/spec/live/ticket_metrics_spec.rb index fae90ffd..d37108ac 100644 --- a/spec/live/ticket_metrics_spec.rb +++ b/spec/live/ticket_metrics_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - describe ZendeskAPI::TicketMetric do it_should_be_readable :ticket_metrics it_should_be_readable ticket, :metrics diff --git a/spec/live/ticket_spec.rb b/spec/live/ticket_spec.rb index 2f0a993e..10c55093 100644 --- a/spec/live/ticket_spec.rb +++ b/spec/live/ticket_spec.rb @@ -1,19 +1,17 @@ -require 'core/spec_helper' - RSpec.describe ZendeskAPI::Ticket do def valid_attributes { - :type => "question", - :subject => "This is a question?", - :comment => { :value => "Indeed it is!" }, - :priority => "normal", - :requester_id => user.id, - :assignee_id => current_user.id, - :submitter_id => user.id, - :collaborator_ids => [agent.id], - :tags => %w(awesome blossom), - :email_ccs => [ - { :user_id => agent.id, action: "put" } + type: "question", + subject: "This is a question?", + comment: {value: "Indeed it is!"}, + priority: "normal", + requester_id: user.id, + assignee_id: current_user.id, + submitter_id: user.id, + collaborator_ids: [agent.id], + tags: %w[awesome blossom], + email_ccs: [ + {user_id: agent.id, action: "put"} ] } end @@ -29,12 +27,12 @@ def valid_attributes describe "#create" do context "when passing large objects as parameters" do - let(:requester) { client.users.search(query: 'role:end-user').detect(&:photo) } + let(:requester) { client.users.search(query: "role:end-user").detect(&:photo) } let(:organization) { client.organizations.sample } let(:ticket_parameters) do { - subject: 'live spec subject', - description: 'live spec description', + subject: "live spec subject", + description: "live spec description", requester: requester, organization: organization } # We should always use requester/organiztion _id for existing records. This test should not be used as a guideline on how to use the sdk. @@ -46,7 +44,7 @@ def valid_attributes end end - it 'is creatable' do + it "is creatable" do expect(requester).to_not be_nil expect(@ticket.id).to_not be_nil @@ -86,17 +84,17 @@ def valid_attributes end it "keeps all the comments", :vcr do - ticket.update(comment: { private: true, body: "Private comment" }) + ticket.update(comment: {private: true, body: "Private comment"}) expect(ticket.attributes_for_save).to eq(ticket: { - "status" => :new, - "comment" => { "private" => true, "body" => "Private comment" } - }) + "status" => :new, + "comment" => {"private" => true, "body" => "Private comment"} + }) - ticket.update(comment: { private: true, body: "Private comment2" }) + ticket.update(comment: {private: true, body: "Private comment2"}) expect(ticket.attributes_for_save).to eq(ticket: { - "status" => :new, - "comment" => { "private" => true, "body" => "Private comment2" } - }) + "status" => :new, + "comment" => {"private" => true, "body" => "Private comment2"} + }) end end @@ -132,7 +130,7 @@ def valid_attributes it "is able to do next" do first = results.to_a.first - stub_json_request(:get, %r{/api/v2/incremental/tickets}, json(:results => [])) + stub_json_request(:get, %r{/api/v2/incremental/tickets}, json(results: [])) results.next expect(results.first).to_not eq(first) @@ -143,8 +141,8 @@ def valid_attributes it "can import" do VCR.use_cassette("ticket_import_can_import") do old = Time.now - (5 * 365 * 24 * 60 * 60) - ticket = ZendeskAPI::Ticket.import(client, valid_attributes.merge(:created_at => old.iso8601)) - expect(ZendeskAPI::Ticket.find(client, :id => ticket.id).created_at.year).to eq(old.year) + ticket = ZendeskAPI::Ticket.import(client, valid_attributes.merge(created_at: old.iso8601)) + expect(ZendeskAPI::Ticket.find(client, id: ticket.id).created_at.year).to eq(old.year) end end @@ -170,11 +168,11 @@ def valid_attributes it "can comment while creating" do VCR.use_cassette("ticket_inline_comments") do ticket = ZendeskAPI::Ticket.new(client, valid_attributes) - ticket.comment = ZendeskAPI::Ticket::Comment.new(client, :value => "My comment", :public => false) + ticket.comment = ZendeskAPI::Ticket::Comment.new(client, value: "My comment", public: false) ticket.save! expect(ticket.changes).to eq({}) # comment was set before save - expect(ticket.attributes[:comment]).to eq({ "value" => "My comment", "public" => false }) + expect(ticket.attributes[:comment]).to eq({"value" => "My comment", "public" => false}) end end @@ -191,7 +189,7 @@ def valid_attributes Thread.current[:response] = response end - ZendeskAPI::Ticket.import(client, :requester => { :email => email, :name => "Hello" }, :subject => "Test", :description => "Test") + ZendeskAPI::Ticket.import(client, requester: {email: email, name: "Hello"}, subject: "Test", description: "Test") end end diff --git a/spec/live/topic_spec.rb b/spec/live/topic_spec.rb index b8aeacea..9cb372e4 100644 --- a/spec/live/topic_spec.rb +++ b/spec/live/topic_spec.rb @@ -1,16 +1,14 @@ -require 'core/spec_helper' - RSpec.describe ZendeskAPI::Topic do def valid_attributes { - :name => "My Topic", - :description => "The mayan calendar ends December 31st. Coincidence? I think not." + name: "My Topic", + description: "The mayan calendar ends December 31st. Coincidence? I think not." } end it_should_be_creatable it_should_be_updatable :title - it_should_be_deletable :create => true + it_should_be_deletable create: true it_should_be_readable :topics it "can upload while creating" do diff --git a/spec/live/topic_subscription_spec.rb b/spec/live/topic_subscription_spec.rb index 0240a6e8..e4f10c94 100644 --- a/spec/live/topic_subscription_spec.rb +++ b/spec/live/topic_subscription_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - describe ZendeskAPI::TopicSubscription, :delete_after, :not_findable do let!(:subscription) do VCR.use_cassette("create_inline_topic_subscription") do diff --git a/spec/live/trigger_category_spec.rb b/spec/live/trigger_category_spec.rb index 54420565..75b8d0d5 100644 --- a/spec/live/trigger_category_spec.rb +++ b/spec/live/trigger_category_spec.rb @@ -1,8 +1,6 @@ -require 'core/spec_helper' - describe ZendeskAPI::TriggerCategory, :delete_after do def valid_attributes - { :name => "New category" } + {name: "New category"} end it_should_be_readable :trigger_categories diff --git a/spec/live/trigger_spec.rb b/spec/live/trigger_spec.rb index a25e2140..f2bcd7b4 100644 --- a/spec/live/trigger_spec.rb +++ b/spec/live/trigger_spec.rb @@ -1,14 +1,12 @@ -require 'core/spec_helper' - describe ZendeskAPI::Trigger, :delete_after do def valid_attributes { - :category_id => "9903501961242", - :title => "my test trigger", - :conditions => { - :all => [{ :field => "status", :operator => "is", :value => "open" }] + category_id: "9903501961242", + title: "my test trigger", + conditions: { + all: [{field: "status", operator: "is", value: "open"}] }, - :actions => [{ :field => "status", :value => "solved" }] + actions: [{field: "status", value: "solved"}] } end @@ -18,7 +16,7 @@ def valid_attributes it_should_be_creatable it_should_be_updatable :conditions, { "any" => [], - "all" => [{ "field" => "priority", "operator" => "is", "value" => "low" }] + "all" => [{"field" => "priority", "operator" => "is", "value" => "low"}] } it_should_be_deletable end diff --git a/spec/live/upload_spec.rb b/spec/live/upload_spec.rb index 6ae8b35b..cb048230 100644 --- a/spec/live/upload_spec.rb +++ b/spec/live/upload_spec.rb @@ -1,8 +1,6 @@ -require 'core/spec_helper' - describe ZendeskAPI::Upload, :not_findable do def valid_attributes - { :file => "spec/fixtures/Argentina.gif" } + {file: "spec/fixtures/Argentina.gif"} end it_should_be_creatable diff --git a/spec/live/user_field_spec.rb b/spec/live/user_field_spec.rb index c53fef31..425128f7 100644 --- a/spec/live/user_field_spec.rb +++ b/spec/live/user_field_spec.rb @@ -1,12 +1,10 @@ -require 'core/spec_helper' - describe ZendeskAPI::UserField, :delete_after do def valid_attributes - { :type => "text", :title => random_string(20), :key => random_string(10) } + {type: "text", title: random_string(20), key: random_string(10)} end - it_should_be_deletable :marked_for_deletion => true + it_should_be_deletable marked_for_deletion: true it_should_be_creatable it_should_be_updatable :title, random_string(22) - it_should_be_readable :user_fields, :create => true + it_should_be_readable :user_fields, create: true end diff --git a/spec/live/user_spec.rb b/spec/live/user_spec.rb index fa66f394..b26a0fa3 100644 --- a/spec/live/user_spec.rb +++ b/spec/live/user_spec.rb @@ -1,47 +1,45 @@ -require 'core/spec_helper' - describe ZendeskAPI::User, :delete_after do def valid_attributes - { name: "Test U.", email: "test+#{Time.now.to_i}@example.org" } + {name: "Test U.", email: "test+#{Time.now.to_i}@example.org"} end it_should_be_creatable it_should_be_updatable :name - it_should_be_deletable :find => [:active?, false] + it_should_be_deletable find: [:active?, false] it_should_be_readable :users it_should_be_readable organization, :users it "should be able to find by email" do VCR.use_cassette("user_find_by_email") do - expect(client.users.search(:query => current_user.email).to_a).to eq([current_user]) + expect(client.users.search(query: current_user.email).to_a).to eq([current_user]) end end describe "related" do it "shows realated users" do VCR.use_cassette("current_user_related_users") do - client.users.search(:query => current_user.email).first + client.users.search(query: current_user.email).first expect(current_user.related).to be_a ZendeskAPI::UserRelated end end end context "passwords", :vcr do - let(:password) { client.config.password || ENV.fetch('PASSWORD', nil) } + let(:password) { client.config.password || ENV.fetch("PASSWORD", nil) } it "sets the password" do - agent.set_password!(:password => password) + agent.set_password!(password: password) end it "changes the password" do - current_user.change_password!(:previous_password => password, :password => password) + current_user.change_password!(previous_password: password, password: password) end end context "side-loading" do context "no permission set" do subject do - VCR.use_cassette("user_admin_role") { client.users.find(:id => 20014182, :include => :roles) } + VCR.use_cassette("user_admin_role") { client.users.find(id: 20014182, include: :roles) } end it "should include role" do @@ -91,8 +89,8 @@ def valid_attributes ZendeskAPI::User.create_many!( client, [ - { name: "one", email: "1@example.org" }, - { name: "two", email: "2@example.org" } + {name: "one", email: "1@example.org"}, + {name: "two", email: "2@example.org"} ] ).tap do |job| job.reload! while job.status != "completed" @@ -145,7 +143,7 @@ def valid_attributes context "permission set" do subject do - VCR.use_cassette("user_permission_set") { client.users.find(:id => 20014327, :include => :roles) } + VCR.use_cassette("user_permission_set") { client.users.find(id: 20014327, include: :roles) } end it "should include role" do diff --git a/spec/live/user_view_spec.rb b/spec/live/user_view_spec.rb index e575e40e..32bfe86e 100644 --- a/spec/live/user_view_spec.rb +++ b/spec/live/user_view_spec.rb @@ -1,11 +1,9 @@ -require 'core/spec_helper' - describe ZendeskAPI::UserView, :delete_after do def valid_attributes { - :title => "Overseas gold member", - :all => [ - { field: "name", operator: "is", value: "abcd" } + title: "Overseas gold member", + all: [ + {field: "name", operator: "is", value: "abcd"} ] } end diff --git a/spec/live/view_spec.rb b/spec/live/view_spec.rb index 0226c1e8..e76b7702 100644 --- a/spec/live/view_spec.rb +++ b/spec/live/view_spec.rb @@ -1,11 +1,9 @@ -require 'core/spec_helper' - describe ZendeskAPI::View, :delete_after do def valid_attributes { - :title => "my test view", - :conditions => { - :all => [{ :field => "status", :operator => "is", :value => "open" }] + title: "my test view", + conditions: { + all: [{field: "status", operator: "is", value: "open"}] } } end @@ -16,7 +14,7 @@ def valid_attributes it_should_be_creatable it_should_be_updatable :conditions, { "any" => [], - "all" => [{ "field" => "status", "operator" => "is", "value" => "solved" }] + "all" => [{"field" => "status", "operator" => "is", "value" => "solved"}] } it_should_be_deletable end diff --git a/spec/live/voice/phone_number_spec.rb b/spec/live/voice/phone_number_spec.rb index 9a39fe60..8fb98be2 100644 --- a/spec/live/voice/phone_number_spec.rb +++ b/spec/live/voice/phone_number_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - describe ZendeskAPI::Voice::PhoneNumber, :delete_after do # We have to find a valid token before we create a phone number def available_phone_token diff --git a/spec/live/webhook_spec.rb b/spec/live/webhook_spec.rb index 8bb030ad..f722a95e 100644 --- a/spec/live/webhook_spec.rb +++ b/spec/live/webhook_spec.rb @@ -1,5 +1,3 @@ -require 'core/spec_helper' - RSpec.describe ZendeskAPI::Webhook, :delete_after do def valid_attributes { diff --git a/spec/macros/resource_macros.rb b/spec/macros/resource_macros.rb index 9a6564ab..902e1cbe 100644 --- a/spec/macros/resource_macros.rb +++ b/spec/macros/resource_macros.rb @@ -8,7 +8,7 @@ def under(object, &blk) let(:parent) { object } define_method(:default_options) do - { "#{object.class.singular_resource_name}_id" => object.id } + {"#{object.class.singular_resource_name}_id" => object.id} end instance_eval(&blk) @@ -20,7 +20,7 @@ def it_should_be_creatable(options = {}) subject { described_class } before(:all) do - VCR.use_cassette("#{described_class.to_s}_create") do + VCR.use_cassette("#{described_class}_create") do @creatable_object = described_class.create!(client, valid_attributes.merge(default_options)) end end @@ -30,26 +30,28 @@ def it_should_be_creatable(options = {}) expect(@creatable_object.send(:id)).to_not be_nil end - it "should be findable", :unless => metadata[:not_findable] do + it "should be findable", unless: metadata[:not_findable] do options = default_options - options.merge!(:id => @creatable_object.id) unless described_class.ancestors.include?(ZendeskAPI::SingularResource) + options[:id] = @creatable_object.id unless described_class.ancestors.include?(ZendeskAPI::SingularResource) expect(described_class.find(client, options)).to eq(@creatable_object) end - after(:all) do - return unless @creatable_object&.id + if metadata[:delete_after] + after(:all) do + return unless @creatable_object&.id - VCR.use_cassette("#{described_class.to_s}_create_delete") do - @creatable_object.destroy + VCR.use_cassette("#{described_class}_create_delete") do + @creatable_object.destroy + end end - end if metadata[:delete_after] + end end end def it_should_be_updatable(attribute, value = "TESTDATA", extra = {}) context "update", :vcr do before(:all) do - VCR.use_cassette("#{described_class.to_s}_update_create") do + VCR.use_cassette("#{described_class}_update_create") do @updatable_object = described_class.create!(client, valid_attributes.merge(default_options)) end end @@ -60,7 +62,7 @@ def it_should_be_updatable(attribute, value = "TESTDATA", extra = {}) end it "should be savable" do - expect(@updatable_object.save).to be(true), "Expected object to save, but it failed with errors: #{@updatable_object.errors&.full_messages&.join(', ')}" + expect(@updatable_object.save).to be(true), "Expected object to save, but it failed with errors: #{@updatable_object.errors&.full_messages&.join(", ")}" end context "after save" do @@ -72,18 +74,20 @@ def it_should_be_updatable(attribute, value = "TESTDATA", extra = {}) expect(@updatable_object.send(attribute)).to eq(value) end - it "should be findable", :unless => metadata[:not_findable] do + it "should be findable", unless: metadata[:not_findable] do options = default_options - options.merge!(:id => @updatable_object.id) unless described_class.ancestors.include?(ZendeskAPI::SingularResource) + options[:id] = @updatable_object.id unless described_class.ancestors.include?(ZendeskAPI::SingularResource) expect(described_class.find(client, options)).to eq(@updatable_object) end end - after(:all) do - VCR.use_cassette("#{described_class.to_s}_update_delete") do - @updatable_object&.destroy + if metadata[:delete_after] + after(:all) do + VCR.use_cassette("#{described_class}_update_delete") do + @updatable_object&.destroy + end end - end if metadata[:delete_after] + end end end @@ -93,7 +97,7 @@ def it_should_be_deletable(options = {}) if options[:object] @deletable_object = options.delete(:object) else - VCR.use_cassette("#{described_class.to_s}_delete_create") do + VCR.use_cassette("#{described_class}_delete_create") do @deletable_object = described_class.create!(client, valid_attributes.merge(default_options)) end end @@ -104,7 +108,7 @@ def it_should_be_deletable(options = {}) expect(@deletable_object.destroyed?).to be(true) if (!options.key?(:find) || options[:find]) && !example.metadata[:not_findable] opts = default_options - opts.merge!(:id => @deletable_object.id) unless described_class.ancestors.include?(ZendeskAPI::SingularResource) + opts[:id] = @deletable_object.id unless described_class.ancestors.include?(ZendeskAPI::SingularResource) obj = described_class.find(client, opts) if options[:find] @@ -121,20 +125,24 @@ def it_should_be_readable(*args) options = args.last.is_a?(Hash) ? args.pop : {} create = !!options.delete(:create) klass = args.first.is_a?(ZendeskAPI::DataResource) ? args.shift : client - context_name = "read_#{klass.class}_#{args.join('_')}" + context_name = "read_#{klass.class}_#{args.join("_")}" context context_name, :vcr do - before(:all) do - VCR.use_cassette("#{described_class.to_s}_#{context_name}_create") do - @readable_object = described_class.create!(client, valid_attributes.merge(default_options)) + if create + before(:all) do + VCR.use_cassette("#{described_class}_#{context_name}_create") do + @readable_object = described_class.create!(client, valid_attributes.merge(default_options)) + end end - end if create + end - after(:all) do - VCR.use_cassette("#{described_class.to_s}_#{context_name}_delete") do - @readable_object.destroy + if create + after(:all) do + VCR.use_cassette("#{described_class}_#{context_name}_delete") do + @readable_object.destroy + end end - end if create + end it "should be findable" do |example| result = klass @@ -161,7 +169,7 @@ def it_should_be_readable(*args) if described_class.respond_to?(:find) && !example.metadata[:not_findable] options = default_options - options.merge!(:id => object.id) unless described_class.ancestors.include?(ZendeskAPI::SingularResource) + options[:id] = object.id unless described_class.ancestors.include?(ZendeskAPI::SingularResource) expect(described_class.find(client, options)).to_not be_nil end end diff --git a/util/resource_handler.rb b/util/resource_handler.rb index 18926b02..64c405a6 100644 --- a/util/resource_handler.rb +++ b/util/resource_handler.rb @@ -1,4 +1,4 @@ -require 'zendesk_api' +require "zendesk_api" class ResourceHandler < YARD::Handlers::Ruby::Base handles method_call(:has), method_call(:has_many) @@ -39,21 +39,21 @@ def process if many reader.signature = "def #{name}=(options = {})" - reader.parameters = [['options', {}]] + reader.parameters = [["options", {}]] reader.docstring.add_tag(YARD::Tags::Tag.new(:param, "Options to pass to the collection object", "Hash", "options")) end writer = YARD::CodeObjects::MethodObject.new(namespace, "#{name}=") register(writer) writer.signature = "def #{name}=(value)" - writer.parameters = [['value', nil]] + writer.parameters = [["value", nil]] writer.dynamic = true writer.docstring.add_tag(YARD::Tags::Tag.new(:return, "The associated object", klass.name)) writer.docstring.add_tag(YARD::Tags::Tag.new(:param, "The associated object or its attributes", "Hash or #{klass.name}", "value")) end def walk_namespace(namespace) - namespace.to_s.split('::').inject(ZendeskAPI) do |klass, namespace| + namespace.to_s.split("::").inject(ZendeskAPI) do |klass, namespace| klass.const_get(namespace) end end diff --git a/util/verb_handler.rb b/util/verb_handler.rb index 128ffec7..641ff8ad 100644 --- a/util/verb_handler.rb +++ b/util/verb_handler.rb @@ -10,7 +10,7 @@ def process verb.docstring.add_tag(YARD::Tags::Tag.new(:return, "Success of this call", "Boolean")) verb.signature = "def #{name}=(options = {})" - verb.parameters = [['options', {}]] + verb.parameters = [["options", {}]] verb.docstring.add_tag(YARD::Tags::Tag.new(:param, "Options to pass to the request", "Hash", "options")) end end diff --git a/zendesk_api.gemspec b/zendesk_api.gemspec index 2903c2f8..a7a9f675 100644 --- a/zendesk_api.gemspec +++ b/zendesk_api.gemspec @@ -1,30 +1,30 @@ -lib = File.expand_path('../lib/', __FILE__) +lib = File.expand_path("lib", __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) -require 'zendesk_api/version' +require "zendesk_api/version" Gem::Specification.new do |s| - s.name = "zendesk_api" - s.version = ZendeskAPI::VERSION - s.authors = ["Steven Davidovitz", "Michael Grosser"] - s.email = ["support@zendesk.com"] - s.homepage = "https://developer.zendesk.com" - s.summary = 'Zendesk REST API Client' - s.description = 'Ruby wrapper for the REST API at https://www.zendesk.com. Documentation at https://developer.zendesk.com.' - s.license = 'Apache-2.0' + s.name = "zendesk_api" + s.version = ZendeskAPI::VERSION + s.authors = ["Steven Davidovitz", "Michael Grosser"] + s.email = ["support@zendesk.com"] + s.homepage = "https://developer.zendesk.com" + s.summary = "Zendesk REST API Client" + s.description = "Ruby wrapper for the REST API at https://www.zendesk.com. Documentation at https://developer.zendesk.com." + s.license = "Apache-2.0" s.metadata = { - 'bug_tracker_uri' => 'https://github.com/zendesk/zendesk_api_client_rb/issues', - 'changelog_uri' => "https://github.com/zendesk/zendesk_api_client_rb/blob/v#{s.version}/CHANGELOG.md", - 'documentation_uri' => "https://www.rubydoc.info/gems/zendesk_api/#{s.version}", - 'source_code_uri' => "https://github.com/zendesk/zendesk_api_client_rb/tree/v#{s.version}", - 'wiki_uri' => 'https://github.com/zendesk/zendesk_api_client_rb/wiki', - 'rubygems_mfa_required' => 'true' + "bug_tracker_uri" => "https://github.com/zendesk/zendesk_api_client_rb/issues", + "changelog_uri" => "https://github.com/zendesk/zendesk_api_client_rb/blob/v#{s.version}/CHANGELOG.md", + "documentation_uri" => "https://www.rubydoc.info/gems/zendesk_api/#{s.version}", + "source_code_uri" => "https://github.com/zendesk/zendesk_api_client_rb/tree/v#{s.version}", + "wiki_uri" => "https://github.com/zendesk/zendesk_api_client_rb/wiki", + "rubygems_mfa_required" => "true" } - s.files = Dir.glob('{lib,util}/**/*') << 'LICENSE' + s.files = Dir.glob("{lib,util}/**/*") << "LICENSE" - s.required_ruby_version = ">= 3.1" + s.required_ruby_version = ">= 3.1" s.required_rubygems_version = ">= 1.3.6" s.add_dependency "faraday", "> 2.0.0"