From e588fa7ece36d2c5aa398ba5eedee6b9d60b0818 Mon Sep 17 00:00:00 2001 From: rhymes Date: Tue, 7 Aug 2018 17:00:13 +0200 Subject: [PATCH] Code cleanups (#659) * Initial automatic cleanup with rubocop * Fix syntax error introduced by rubocop * Cleanup seeds file * Cleanup lib folder * Exclude bin folder because it contains auto generated files * Make Rubocop a little bit more chatty * Block length should not include comments in the count * Cleanup config folder * Cleanup specs * Updated Rubocop version and generated a todo file * Fix broken ArticlesApi spec * Fix tests * Restored rubocop pre-commit hook --- .rubocop.yml | 10 +- .rubocop_todo.yml | 200 ++++++++++++++++++ Gemfile | 2 +- Gemfile.lock | 6 +- Guardfile | 6 +- Rakefile | 2 +- app/black_box/black_box.rb | 12 +- .../additional_content_boxes_controller.rb | 4 +- .../admin/application_controller.rb | 2 +- app/controllers/api/v0/api_controller.rb | 22 +- app/controllers/api/v0/articles_controller.rb | 6 +- app/controllers/api/v0/comments_controller.rb | 14 +- app/controllers/api/v0/follows_controller.rb | 4 +- .../api/v0/podcast_episodes_controller.rb | 9 +- .../api/v0/reactions_controller.rb | 2 +- app/controllers/api/v0/users_controller.rb | 10 +- app/controllers/articles_controller.rb | 14 +- app/controllers/async_info_controller.rb | 10 +- app/controllers/blocks_controller.rb | 4 +- .../chat_channel_memberships_controller.rb | 4 +- app/controllers/chat_channels_controller.rb | 33 ++- app/controllers/dashboards_controller.rb | 2 +- .../followed_articles_controller.rb | 10 +- app/controllers/github_repos_controller.rb | 2 +- app/controllers/giveaways_controller.rb | 98 ++++----- app/controllers/image_uploads_controller.rb | 8 +- .../internal/application_controller.rb | 10 +- .../internal/articles_controller.rb | 2 +- .../internal/buffer_updates_controller.rb | 2 +- .../internal/comments_controller.rb | 34 +-- .../internal/dogfood_controller.rb | 3 +- .../internal/feedback_messages_controller.rb | 2 +- app/controllers/internal/tags_controller.rb | 21 +- app/controllers/internal/users_controller.rb | 4 +- app/controllers/messages_controller.rb | 2 +- .../notifications/reads_controller.rb | 1 - app/controllers/notifications_controller.rb | 2 +- app/controllers/pages_controller.rb | 5 +- .../podcast_episodes_controller.rb | 7 +- app/controllers/pusher_controller.rb | 8 +- app/controllers/reactions_controller.rb | 8 +- app/controllers/registrations_controller.rb | 2 +- app/controllers/stories_controller.rb | 41 ++-- app/controllers/twilio_tokens_controller.rb | 2 +- app/controllers/videos_controller.rb | 2 +- app/dashboards/article_dashboard.rb | 73 ++++--- app/dashboards/badge_achievement_dashboard.rb | 38 ++-- app/dashboards/badge_dashboard.rb | 40 ++-- app/dashboards/collection_dashboard.rb | 64 +++--- app/dashboards/comment_dashboard.rb | 54 ++--- app/dashboards/dashboard_manifest.rb | 34 +-- app/dashboards/display_ad_dashboard.rb | 54 ++--- app/dashboards/email_message_dashboard.rb | 44 ++-- app/dashboards/feedback_message_dashboard.rb | 32 +-- app/dashboards/follow_dashboard.rb | 34 +-- app/dashboards/organization_dashboard.rb | 64 +++--- app/dashboards/podcast_dashboard.rb | 88 ++++---- app/dashboards/podcast_episode_dashboard.rb | 66 +++--- app/dashboards/reaction_dashboard.rb | 38 ++-- app/dashboards/tag_dashboard.rb | 88 ++++---- app/dashboards/user_dashboard.rb | 66 +++--- app/decorators/article_decorator.rb | 2 +- app/decorators/organization_decorator.rb | 8 +- app/decorators/user_decorator.rb | 86 ++++---- app/helpers/application_helper.rb | 26 +-- app/helpers/articles_helper.rb | 13 +- app/labor/badge_rewarder.rb | 9 +- app/labor/cache_buster.rb | 21 +- app/labor/color_from_image.rb | 9 +- app/labor/error_message_cleaner.rb | 2 - app/labor/follow_checker.rb | 1 - app/labor/hex_comparer.rb | 46 ++-- app/labor/html_cleaner.rb | 11 +- app/labor/language_detector.rb | 13 +- app/labor/markdown_parser.rb | 2 +- app/labor/notification_counter.rb | 5 +- app/labor/podcast_feed.rb | 18 +- app/labor/rate_limit_checker.rb | 22 +- app/labor/reaction_image.rb | 10 +- app/labor/reading_list.rb | 2 +- app/labor/timeframer.rb | 4 +- app/labor/twilio_token.rb | 3 +- app/labor/unread_notifications_emailer.rb | 14 +- app/labor/user_states.rb | 12 +- app/liquid_tags/codepen_tag.rb | 2 +- app/liquid_tags/comment_tag.rb | 24 +-- app/liquid_tags/gist_tag.rb | 2 +- app/liquid_tags/github_tag.rb | 18 +- .../github_tag/github_issue_tag.rb | 24 +-- .../github_tag/github_readme_tag.rb | 11 +- app/liquid_tags/glitch_tag.rb | 2 +- app/liquid_tags/instagram_tag.rb | 24 +-- app/liquid_tags/link_tag.rb | 6 +- app/liquid_tags/liquid_tag_base.rb | 12 +- app/liquid_tags/podcast_tag.rb | 75 ++++--- app/liquid_tags/replit_tag.rb | 10 +- app/liquid_tags/speakerdeck_tag.rb | 2 +- app/liquid_tags/tweet_tag.rb | 46 ++-- app/liquid_tags/user_tag.rb | 12 +- app/liquid_tags/youtube_tag.rb | 8 +- app/models/article.rb | 102 ++++----- app/models/block.rb | 4 +- app/models/comment.rb | 65 +++--- app/models/display_ad.rb | 2 +- app/models/email_message.rb | 6 +- app/models/follow.rb | 13 +- app/models/github_issue.rb | 2 +- app/models/github_repo.rb | 8 +- app/models/mention.rb | 16 +- app/models/message.rb | 8 +- app/models/notification.rb | 12 +- app/models/organization.rb | 6 +- app/models/podcast.rb | 1 - app/models/podcast_episode.rb | 48 ++--- app/models/reaction.rb | 14 +- app/models/tag.rb | 2 +- app/observers/article_observer.rb | 2 +- app/observers/reaction_observer.rb | 2 +- .../chat_channel_membership_policy.rb | 2 +- app/policies/chat_channel_policy.rb | 2 - app/policies/comment_policy.rb | 2 +- app/services/article_api_index_service.rb | 28 +-- app/services/authorization_service.rb | 4 +- app/services/chat_channel_creation_service.rb | 4 +- app/services/chat_channel_update_service.rb | 2 +- .../get_unseen_notifications_service.rb | 1 - app/services/membership_service.rb | 6 +- app/services/read_notifications_service.rb | 1 - .../suggester/articles/high_quality.rb | 14 +- app/services/user_role_service.rb | 4 +- app/uploaders/article_image_uploader.rb | 2 +- app/views/api/v0/articles/index.json.jbuilder | 3 +- app/views/api/v0/articles/show.json.jbuilder | 2 +- app/views/api/v0/comments/index.json.jbuilder | 2 +- app/views/api/v0/tags/index.json.jbuilder | 2 +- .../api/v0/tags/onboarding.json.jbuilder | 2 +- app/views/api/v0/users/show.json.jbuilder | 2 +- app/views/articles/feed.rss.builder | 7 +- app/views/chat_channels/index.json.jbuilder | 2 +- bin/_guard-core | 1 + bin/bundle | 166 +++++++-------- bin/delayed_job | 4 +- bin/guard | 1 + bin/parallel_rspec | 4 +- bin/rails | 10 +- bin/rake | 8 +- bin/rspec | 1 + bin/rspecov | 4 +- bin/setup | 2 +- bin/spring | 8 +- bin/startup | 2 +- bin/update | 18 +- bin/webpack | 2 +- bin/webpack-dev-server | 14 +- bin/yarn | 14 +- config.ru | 2 +- config/application.rb | 16 +- config/boot.rb | 4 +- config/environment.rb | 2 +- config/environments/development.rb | 22 +- config/environments/production.rb | 57 ++--- config/environments/test.rb | 5 +- config/initializers/0_application_config.rb | 2 +- config/initializers/algoliasearch.rb | 21 +- config/initializers/assets.rb | 20 +- config/initializers/backtrace_silencers.rb | 6 +- config/initializers/devise.rb | 12 +- config/initializers/fastly.rb | 10 +- config/initializers/octokit.rb | 2 +- .../persistent_csrf_token_cookie.rb | 7 +- config/initializers/redcarpet.rb | 2 +- config/initializers/rolify.rb | 2 +- config/initializers/s3_direct_upload.rb | 12 +- config/initializers/session_store.rb | 2 +- config/initializers/slack_notifier.rb | 2 +- config/initializers/timber.rb | 1 - config/puma.rb | 4 +- config/routes.rb | 124 ++++++----- db/seeds.rb | 66 +++++- lib/api_constraints.rb | 2 +- lib/tasks/db.rake | 2 + lib/tasks/fetch.rake | 37 ++-- lib/tasks/linters.rake | 2 +- spec/factories/articles.rb | 4 +- spec/factories/badge_achievements.rb | 2 +- spec/factories/badges.rb | 6 +- spec/factories/blocks.rb | 6 +- spec/factories/chat_channels.rb | 2 +- spec/factories/comments.rb | 2 +- spec/factories/display_ads.rb | 4 +- spec/factories/events.rb | 2 +- spec/factories/feedback_messages.rb | 15 +- spec/factories/github_repos.rb | 4 +- spec/factories/identities.rb | 2 +- spec/factories/mentions.rb | 4 +- spec/factories/notifications.rb | 2 +- spec/factories/podcasts.rb | 6 +- spec/factories/reactions.rb | 4 +- spec/factories/tags.rb | 2 +- spec/factories/users.rb | 12 +- spec/features/admin_bans_a_user_spec.rb | 15 +- spec/features/admin_creates_new_event_spec.rb | 11 +- spec/features/admin_sends_a_broadcast_spec.rb | 6 +- spec/features/admin_warns_a_user_spec.rb | 13 +- .../features/banned_user_interactions_spec.rb | 4 +- spec/features/user_deletes_an_article_spec.rb | 4 +- spec/features/user_edits_an_article_spec.rb | 11 +- spec/features/user_fills_out_comment_spec.rb | 4 +- .../user_fills_out_givaway_form_spec.rb | 8 +- .../user_sees_checklist_on_home_page_spec.rb | 22 +- .../features/user_selects_looking_for_work.rb | 6 +- .../user_updates_org_settings_spec.rb | 14 +- .../user_views_and_closes_onboarding_spec.rb | 3 +- .../features/user_visits_podcast_show_spec.rb | 46 ++-- spec/features/user_visits_tags_page_spec.rb | 34 +-- spec/labor/article_suggester_spec.rb | 21 +- spec/labor/badge_rewarder_spec.rb | 18 +- spec/labor/bufferizer_spec.rb | 4 +- spec/labor/cache_buster_spec.rb | 21 +- spec/labor/color_from_image_spec.rb | 7 +- spec/labor/email_digest_spec.rb | 2 +- spec/labor/email_logic_spec.rb | 16 +- spec/labor/follow_checker_spec.rb | 13 +- spec/labor/generated_image_spec.rb | 25 +-- spec/labor/hex_comparer_spec.rb | 9 +- spec/labor/language_detector_spec.rb | 7 +- spec/labor/mailchimp_bot_spec.rb | 40 ++-- spec/labor/markdown_parser_spec.rb | 6 - spec/labor/rate_limit_checker_spec.rb | 54 +++-- spec/labor/reaction_image_spec.rb | 10 +- spec/labor/reading_list_spec.rb | 71 +++---- spec/labor/rss_reader_spec.rb | 3 +- spec/labor/twilio_token_spec.rb | 4 +- .../acts_as_taggable_on/tag_parser_spec.rb | 24 +-- spec/liquid_tags/comment_tag_spec.rb | 17 +- .../{ => github_tag}/github_issue_tag_spec.rb | 0 .../github_readme_tag_spec.rb | 9 +- spec/liquid_tags/instagram_tag_spec.rb | 2 +- spec/liquid_tags/podcast_tag_spec.rb | 16 +- spec/liquid_tags/replit_tag_spec.rb | 13 +- ...ck_tag_spec.rb => speakerdeck_tag_spec.rb} | 2 +- spec/liquid_tags/user_tag_spec.rb | 15 +- spec/liquid_tags/youtube_tag_spec.rb | 29 +-- spec/mailers/membership_mailer_spec.rb | 9 +- spec/mailers/notify_mailer_spec.rb | 19 +- spec/models/article_spec.rb | 59 +++--- spec/models/block_spec.rb | 17 +- spec/models/chat_channel_spec.rb | 6 + spec/models/comment_spec.rb | 16 +- spec/models/display_ad_spec.rb | 10 +- spec/models/event_spec.rb | 2 +- spec/models/follow_spec.rb | 5 +- spec/models/job_opportunity_spec.rb | 2 +- spec/models/mention_spec.rb | 51 +++-- spec/models/message_spec.rb | 19 +- spec/models/notification_spec.rb | 21 +- spec/models/podcast_episode_spec.rb | 6 +- spec/models/reaction_spec.rb | 24 ++- spec/models/search_keyword_spec.rb | 6 +- spec/models/tag_spec.rb | 2 +- spec/models/user_spec.rb | 109 ++++++---- spec/policies/admin_policy_spec.rb | 16 +- .../chat_channel_membership_policy_spec.rb | 19 +- spec/policies/chat_channel_policy_spec.rb | 5 + spec/policies/comment_policy_spec.rb | 8 +- spec/policies/image_upload_policy_spec.rb | 2 +- spec/policies/reaction_policy_spec.rb | 3 +- spec/policies/user_policy_spec.rb | 6 +- spec/policies/video_policy_spec.rb | 7 +- spec/rails_helper.rb | 32 +-- .../requests/additional_content_boxes_spec.rb | 5 +- spec/requests/articles_api_spec.rb | 19 +- spec/requests/articles_create_spec.rb | 26 ++- spec/requests/articles_update_spec.rb | 4 +- spec/requests/async_info_spec.rb | 36 +++- spec/requests/blocks_spec.rb | 13 +- .../requests/chat_channel_memberships_spec.rb | 33 ++- spec/requests/chat_channels_spec.rb | 56 ++--- spec/requests/comments_api_spec.rb | 14 +- spec/requests/comments_spec.rb | 4 +- spec/requests/dashboard_spec.rb | 1 - spec/requests/events_spec.rb | 14 +- spec/requests/feature_toggle_spec.rb | 2 +- .../requests/feedback_messages_create_spec.rb | 2 + spec/requests/followed_articles_spec.rb | 9 +- spec/requests/follows_api_spec.rb | 16 +- spec/requests/image_uploads_spec.rb | 23 +- spec/requests/notification_counts_spec.rb | 2 +- spec/requests/notifications_spec.rb | 1 + spec/requests/organizations_update_spec.rb | 2 +- spec/requests/pages_spec.rb | 3 +- spec/requests/podcast_episodes_api_spec.rb | 13 +- spec/requests/pusher_auth_spec.rb | 3 +- spec/requests/reactions_api_spec.rb | 23 +- spec/requests/reactions_spec.rb | 2 +- spec/requests/reading_list_index_spec.rb | 1 + spec/requests/rss_feed_spec.rb | 19 +- spec/requests/social_previews_spec.rb | 30 +-- spec/requests/stories_index_spec.rb | 15 +- spec/requests/stories_show_spec.rb | 85 ++++---- spec/requests/stripe_active_cards_spec.rb | 1 - spec/requests/stripe_subscriptions_spec.rb | 3 +- spec/requests/tags_api_spec.rb | 2 + spec/requests/twilio_tokens_spec.rb | 2 +- spec/requests/users_api_spec.rb | 6 +- spec/requests/users_onboarding_spec.rb | 7 +- spec/requests/videos_spec.rb | 12 +- spec/routing/all_routes_spec.rb | 7 +- spec/services/membership_service_spec.rb | 7 +- .../suggester/articles/boosted_spec.rb | 10 +- .../suggester/articles/classic_spec.rb | 16 +- spec/services/suggester/users/recent_spec.rb | 4 +- spec/services/suggester/users/sidebar_spec.rb | 4 +- spec/services/user_role_service_spec.rb | 6 +- spec/spec_helper.rb | 82 ++++--- spec/support/database_cleaner.rb | 6 +- spec/support/fake_stream.rb | 8 +- spec/support/request_spec_helper.rb | 4 +- spec/support/shared_context.rb | 4 +- spec/support/stubs.rb | 86 ++++++-- spec/views/articles_spec.rb | 15 +- 321 files changed, 2854 insertions(+), 2393 deletions(-) create mode 100644 .rubocop_todo.yml rename spec/liquid_tags/{ => github_tag}/github_issue_tag_spec.rb (100%) rename spec/liquid_tags/{ => github_tag}/github_readme_tag_spec.rb (83%) rename spec/liquid_tags/{speakereck_tag_spec.rb => speakerdeck_tag_spec.rb} (90%) diff --git a/.rubocop.yml b/.rubocop.yml index 9f38c43c5a09a..05fbd820eefc0 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,3 +1,5 @@ +inherit_from: .rubocop_todo.yml + require: rubocop-rspec # our custom config @@ -19,7 +21,13 @@ Metrics/LineLength: AllCops: Exclude: + - bin/**/* - db/schema.rb + - db/migrate/*.rb + - node_modules/**/* + DisplayStyleGuide: true + ExtraDetails: true + TargetRubyVersion: 2.5 Naming/AccessorMethodName: Description: Check the naming of accessor methods for get_/set_. @@ -110,7 +118,7 @@ Metrics/AbcSize: Enabled: false Metrics/BlockLength: - CountComments: true # count full line comments? + CountComments: false # count full line comments? Max: 25 ExcludedMethods: [] Exclude: diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml new file mode 100644 index 0000000000000..fd7c31fd8ff83 --- /dev/null +++ b/.rubocop_todo.yml @@ -0,0 +1,200 @@ +# This configuration was generated by +# `rubocop --auto-gen-config` +# on 2018-08-05 17:42:25 +0200 using RuboCop version 0.58.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: 9 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyleAlignWith, AutoCorrect, Severity. +# SupportedStylesAlignWith: keyword, variable, start_of_line +Layout/EndAlignment: + Exclude: + - 'app/controllers/api/v0/articles_controller.rb' + - 'app/controllers/articles_controller.rb' + - 'app/controllers/chat_channels_controller.rb' + - 'app/controllers/image_uploads_controller.rb' + - 'app/helpers/application_helper.rb' + - 'app/models/user.rb' + - 'app/services/article_api_index_service.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBrackets. +# SupportedStyles: space, no_space, compact +# SupportedStylesForEmptyBrackets: space, no_space +Layout/SpaceInsideArrayLiteralBrackets: + Exclude: + - 'app/dashboards/email_message_dashboard.rb' + +# Offense count: 3 +Lint/AmbiguousBlockAssociation: + Exclude: + - 'app/controllers/podcast_episodes_controller.rb' + - 'app/views/api/v0/articles/show.json.jbuilder' + +# Offense count: 4 +Lint/IneffectiveAccessModifier: + Exclude: + - 'app/black_box/black_box.rb' + - 'app/models/tweet.rb' + +# Offense count: 3 +Lint/ShadowingOuterLocalVariable: + Exclude: + - 'app/views/api/v0/comments/index.json.jbuilder' + - 'app/views/api/v0/comments/show.json.jbuilder' + +# Offense count: 2 +# Configuration parameters: ContextCreatingMethods, MethodCreatingMethods. +Lint/UselessAccessModifier: + Exclude: + - 'app/black_box/black_box.rb' + - 'app/models/tweet.rb' + +# Offense count: 10 +Lint/UselessAssignment: + Exclude: + - 'app/controllers/stories_controller.rb' + - 'app/labor/cache_buster.rb' + - 'app/labor/markdown_parser.rb' + - 'app/labor/rate_limit_checker.rb' + - 'app/liquid_tags/comment_tag.rb' + - 'app/liquid_tags/glitch_tag.rb' + - 'app/liquid_tags/tweet_tag.rb' + +# Offense count: 8 +# Configuration parameters: CountComments, ExcludedMethods. +# ExcludedMethods: refine +Metrics/BlockLength: + Max: 68 + +# Offense count: 132 +# Configuration parameters: AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns. +# URISchemes: http, https +Metrics/LineLength: + Max: 274 + +# Offense count: 14 +Metrics/PerceivedComplexity: + Max: 16 + +# Offense count: 1 +# Configuration parameters: EnforcedStyleForLeadingUnderscores. +# SupportedStylesForLeadingUnderscores: disallowed, required, optional +Naming/MemoizedInstanceVariableName: + Exclude: + - 'app/controllers/admin/application_controller.rb' + +# Offense count: 2 +# Configuration parameters: EnforcedStyle. +# SupportedStyles: snake_case, camelCase +Naming/MethodName: + Exclude: + - 'app/helpers/articles_helper.rb' + - 'app/liquid_tags/podcast_tag.rb' + +# Offense count: 4 +# Configuration parameters: NamePrefix, NamePrefixBlacklist, NameWhitelist, MethodDefinitionMacros. +# NamePrefix: is_, has_, have_ +# NamePrefixBlacklist: is_, has_, have_ +# NameWhitelist: is_a? +# MethodDefinitionMacros: define_method, define_singleton_method +Naming/PredicateName: + Exclude: + - 'spec/**/*' + - 'app/controllers/application_controller.rb' + - 'app/helpers/articles_helper.rb' + - 'app/models/user.rb' + +# Offense count: 9 +# Configuration parameters: MinNameLength, AllowNamesEndingInNumbers, AllowedNames, ForbiddenNames. +# AllowedNames: io, id, to, by, on, in, at, ip +Naming/UncommunicativeMethodParamName: + Exclude: + - 'app/controllers/followed_articles_controller.rb' + - 'app/controllers/internal/dogfood_controller.rb' + - 'app/labor/mailchimp_bot.rb' + - 'app/labor/podcast_feed.rb' + - 'app/models/chat_channel.rb' + - 'app/models/tweet.rb' + +# Offense count: 2 +# Configuration parameters: EnforcedStyle. +# SupportedStyles: snake_case, camelCase +Naming/VariableName: + Exclude: + - 'app/liquid_tags/github_tag/github_issue_tag.rb' + +# Offense count: 3 +Security/Open: + Exclude: + - 'app/labor/podcast_feed.rb' + - 'app/labor/rss_reader.rb' + +# Offense count: 14 +# Cop supports --auto-correct. +# Configuration parameters: AutoCorrect, EnforcedStyle. +# SupportedStyles: nested, compact +Style/ClassAndModuleChildren: + Exclude: + - 'app/controllers/api/v0/api_controller.rb' + - 'app/controllers/internal/application_controller.rb' + - 'app/controllers/internal/articles_controller.rb' + - 'app/controllers/internal/broadcasts_controller.rb' + - 'app/controllers/internal/buffer_updates_controller.rb' + - 'app/controllers/internal/comments_controller.rb' + - 'app/controllers/internal/dogfood_controller.rb' + - 'app/controllers/internal/feedback_messages_controller.rb' + - 'app/controllers/internal/members_controller.rb' + - 'app/controllers/internal/tags_controller.rb' + - 'app/controllers/internal/users_controller.rb' + - 'app/controllers/internal/welcome_controller.rb' + - 'app/controllers/notifications/counts_controller.rb' + - 'app/controllers/notifications/reads_controller.rb' + +# Offense count: 1 +Style/DateTime: + Exclude: + - 'app/controllers/comments_controller.rb' + +# Offense count: 1 +Style/EvalWithLocation: + Exclude: + - 'app/controllers/omniauth_callbacks_controller.rb' + +# Offense count: 1 +# Configuration parameters: EnforcedStyle. +# SupportedStyles: each, for +Style/For: + Exclude: + - 'app/views/articles/feed.rss.builder' + +# Offense count: 1 +Style/IfInsideElse: + Exclude: + - 'app/models/comment.rb' + +# Offense count: 3 +Style/MixinUsage: + Exclude: + - 'app/models/organization.rb' + - 'app/models/podcast_episode.rb' + +# Offense count: 1 +# Cop supports --auto-correct. +# Configuration parameters: AutoCorrect, EnforcedStyle. +# SupportedStyles: predicate, comparison +Style/NumericPredicate: + Exclude: + - 'spec/**/*' + - 'app/liquid_tags/github_tag/github_issue_tag.rb' + +# Offense count: 3 +# Cop supports --auto-correct. +# Configuration parameters: AllowAsExpressionSeparator. +Style/Semicolon: + Exclude: + - 'app/controllers/stories_controller.rb' diff --git a/Gemfile b/Gemfile index 60807463d49db..bc642e4b840ef 100644 --- a/Gemfile +++ b/Gemfile @@ -10,7 +10,7 @@ git_source(:github) do |repo_name| end group :production do - gem 'nakayoshi_fork' + gem "nakayoshi_fork" end gem "actionpack-action_caching", "~> 1.2" diff --git a/Gemfile.lock b/Gemfile.lock index 116b1c2789181..c8a29710a5857 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -617,7 +617,7 @@ GEM parallel (1.12.1) parallel_tests (2.21.3) parallel - parser (2.5.1.0) + parser (2.5.1.2) ast (~> 2.4.0) pg (0.21.0) powerpack (0.1.2) @@ -736,10 +736,10 @@ GEM rspec-retry (0.6.1) rspec-core (> 3.3) rspec-support (3.7.1) - rubocop (0.57.2) + rubocop (0.58.2) jaro_winkler (~> 1.5.1) parallel (~> 1.10) - parser (>= 2.5) + parser (>= 2.5, != 2.5.1.1) powerpack (~> 0.1) rainbow (>= 2.2.2, < 4.0) ruby-progressbar (~> 1.7) diff --git a/Guardfile b/Guardfile index 915243a85ecef..06eb1aa8668d5 100644 --- a/Guardfile +++ b/Guardfile @@ -27,7 +27,7 @@ ignore([%r{^bin/*}, %r{^config/*}, %r{^db/*}, %r{^lib/*}, %r{^log/*}, %r{^public/*}, %r{^tmp/*}, %r{^node_modules/*}]) rspec_options = { - results_file: File.expand_path('tmp/guard_rspec_results.txt'), + results_file: File.expand_path("tmp/guard_rspec_results.txt"), ############################# # BECAUSE spring doesn't seem to work well with simplecov, choose # between the following two. @@ -37,7 +37,7 @@ rspec_options = { cmd: "bin/spring rspec -p", ############################# failed_mode: :focus, - bundler_env: :clean_env + bundler_env: :clean_env, } guard :rspec, rspec_options do @@ -65,7 +65,7 @@ guard :rspec, rspec_options do [ rspec.spec.call("routing/#{m[1]}_routing"), rspec.spec.call("controllers/#{m[1]}_controller"), - rspec.spec.call("acceptance/#{m[1]}") + rspec.spec.call("acceptance/#{m[1]}"), ] end diff --git a/Rakefile b/Rakefile index ba6b733dd2358..08cc98f381dbd 100644 --- a/Rakefile +++ b/Rakefile @@ -1,6 +1,6 @@ # Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. -require File.expand_path('../config/application', __FILE__) +require File.expand_path("config/application", __dir__) Rails.application.load_tasks diff --git a/app/black_box/black_box.rb b/app/black_box/black_box.rb index 05fc0795e92c3..38b6bb9de3403 100644 --- a/app/black_box/black_box.rb +++ b/app/black_box/black_box.rb @@ -1,16 +1,16 @@ class BlackBox def self.article_hotness_score(article) - return (article.featured_number|| 10000)/10000 unless Rails.env.production? + return (article.featured_number || 10000) / 10000 unless Rails.env.production? reaction_points = article.reactions.sum(:points) recency_bonus = article.published_at > 12.hours.ago ? 50 : 0 today_bonus = article.published_at > 36.hours.ago ? 250 : 0 FunctionCaller.new("blackbox-production-articleHotness", - {article: article, user: article.user}.to_json).call + + { article: article, user: article.user }.to_json).call + reaction_points + recency_bonus + today_bonus end def self.comment_quality_score(comment) - descendants_points = (comment.descendants.size/2) + descendants_points = (comment.descendants.size / 2) rep_points = comment.reactions.sum(:points) bonus_points = calculate_bonus_score(comment.body_markdown) spaminess_rating = calculate_spaminess(comment) @@ -18,18 +18,18 @@ def self.comment_quality_score(comment) end def self.calculate_spaminess(story) - #accepts comment or article as story + # accepts comment or article as story return 0 unless Rails.env.production? return 100 unless story.user FunctionCaller.new("blackbox-production-spamScore", - {story: story, user: story.user}.to_json).call + { story: story, user: story.user }.to_json).call end private def self.calculate_bonus_score(body_markdown) size_bonus = body_markdown.size > 200 ? 2 : 0 - code_bonus = body_markdown.include?('`') ? 1 : 0 + code_bonus = body_markdown.include?("`") ? 1 : 0 size_bonus + code_bonus end end diff --git a/app/controllers/additional_content_boxes_controller.rb b/app/controllers/additional_content_boxes_controller.rb index 42b42be912b8c..7c45e851566c3 100644 --- a/app/controllers/additional_content_boxes_controller.rb +++ b/app/controllers/additional_content_boxes_controller.rb @@ -14,11 +14,11 @@ def index @boosted_article = Suggester::Articles::Boosted.new( current_user, @article, - {not_ids: (article_ids + [@for_user_article&.id]), area: "additional_articles"}, + not_ids: (article_ids + [@for_user_article&.id]), area: "additional_articles", ).suggest else @alt_classic = Suggester::Articles::Classic. - new(@article, {not_ids: (article_ids + [@for_user_article&.id])}).get + new(@article, not_ids: (article_ids + [@for_user_article&.id])).get end set_surrogate_key_header "additional_content_boxes_" + params.to_s unless current_user render "boxes", layout: false diff --git a/app/controllers/admin/application_controller.rb b/app/controllers/admin/application_controller.rb index aab00b3c7dbbb..de0239108d610 100644 --- a/app/controllers/admin/application_controller.rb +++ b/app/controllers/admin/application_controller.rb @@ -10,7 +10,7 @@ class ApplicationController < Administrate::ApplicationController before_action :authorize_admin def order - @_order ||= Administrate::Order.new(params[:order] || "id",params[:direction] || "desc") + @_order ||= Administrate::Order.new(params[:order] || "id", params[:direction] || "desc") end def valid_request_origin? diff --git a/app/controllers/api/v0/api_controller.rb b/app/controllers/api/v0/api_controller.rb index dd88cbbbd2810..664e6511b2d71 100644 --- a/app/controllers/api/v0/api_controller.rb +++ b/app/controllers/api/v0/api_controller.rb @@ -1,19 +1,19 @@ class Api::V0::ApiController < ApplicationController def cors_set_access_control_headers - headers['Access-Control-Allow-Origin'] = '*' - headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, OPTIONS' - headers['Access-Control-Allow-Headers'] = 'Origin, Content-Type, Accept, Authorization, Token' - headers['Access-Control-Max-Age'] = "1728000" + headers["Access-Control-Allow-Origin"] = "*" + headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS" + headers["Access-Control-Allow-Headers"] = "Origin, Content-Type, Accept, Authorization, Token" + headers["Access-Control-Max-Age"] = "1728000" end def cors_preflight_check - if request.method == 'OPTIONS' - headers['Access-Control-Allow-Origin'] = '*' - headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, OPTIONS' - headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-Prototype-Version, Token' - headers['Access-Control-Max-Age'] = '1728000' + if request.method == "OPTIONS" + headers["Access-Control-Allow-Origin"] = "*" + headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS" + headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-Prototype-Version, Token" + headers["Access-Control-Max-Age"] = "1728000" - render :text => '', :content_type => 'text/plain' + render text: "", content_type: "text/plain" end end -end \ No newline at end of file +end diff --git a/app/controllers/api/v0/articles_controller.rb b/app/controllers/api/v0/articles_controller.rb index 273bd20c43e06..71a4f1fb14bad 100644 --- a/app/controllers/api/v0/articles_controller.rb +++ b/app/controllers/api/v0/articles_controller.rb @@ -55,9 +55,9 @@ def create def update @article = Article.find(params[:id]) render json: if @article.update(article_params) - @article.to_json(only: [:id], methods: [:current_state_path]) - else - @article.errors.to_json + @article.to_json(only: [:id], methods: [:current_state_path]) + else + @article.errors.to_json end end diff --git a/app/controllers/api/v0/comments_controller.rb b/app/controllers/api/v0/comments_controller.rb index 5d1c0f3b910b3..8f69a30651989 100644 --- a/app/controllers/api/v0/comments_controller.rb +++ b/app/controllers/api/v0/comments_controller.rb @@ -1,27 +1,25 @@ module Api module V0 class CommentsController < ApplicationController - # before_action :set_cache_control_headers, only: [:index, :show] caches_action :index, - :cache_path => Proc.new { |c| c.params.permit! }, - :expires_in => 10.minutes + cache_path: Proc.new { |c| c.params.permit! }, + expires_in: 10.minutes respond_to :json caches_action :show, - :cache_path => Proc.new { |c| c.params.permit! }, - :expires_in => 10.minutes + cache_path: Proc.new { |c| c.params.permit! }, + expires_in: 10.minutes respond_to :json def index - @commentable = Article.find(params[:a_id])# or not_found + @commentable = Article.find(params[:a_id]) # or not_found @commentable_type = "Article" end def show - @comment = Comment.find(params[:id].to_i(26)) or not_found + (@comment = Comment.find(params[:id].to_i(26))) || not_found end - end end end diff --git a/app/controllers/api/v0/follows_controller.rb b/app/controllers/api/v0/follows_controller.rb index 7fbf96511e66a..75f52318f336b 100644 --- a/app/controllers/api/v0/follows_controller.rb +++ b/app/controllers/api/v0/follows_controller.rb @@ -5,11 +5,11 @@ def create return unless user_signed_in? users = JSON.parse(params[:users]) users.each do |user_hash| - followable = User.find(user_hash['id']) + followable = User.find(user_hash["id"]) current_user.delay.follow(followable) end render json: { outcome: "followed 50 users" } end end end -end \ No newline at end of file +end diff --git a/app/controllers/api/v0/podcast_episodes_controller.rb b/app/controllers/api/v0/podcast_episodes_controller.rb index c0a687ac3db28..1dc456e9f9d13 100644 --- a/app/controllers/api/v0/podcast_episodes_controller.rb +++ b/app/controllers/api/v0/podcast_episodes_controller.rb @@ -1,16 +1,15 @@ module Api module V0 class PodcastEpisodesController < ApiController - # before_action :set_cache_control_headers, only: [:index, :show] caches_action :index, - :cache_path => Proc.new { |c| c.params.permit! }, - :expires_in => 10.minutes + cache_path: Proc.new { |c| c.params.permit! }, + expires_in: 10.minutes respond_to :json caches_action :show, - :cache_path => Proc.new { |c| c.params.permit! }, - :expires_in => 10.minutes + cache_path: Proc.new { |c| c.params.permit! }, + expires_in: 10.minutes respond_to :json before_action :cors_preflight_check diff --git a/app/controllers/api/v0/reactions_controller.rb b/app/controllers/api/v0/reactions_controller.rb index 091c264c09cd5..4ebc4cb5b7da8 100644 --- a/app/controllers/api/v0/reactions_controller.rb +++ b/app/controllers/api/v0/reactions_controller.rb @@ -5,7 +5,7 @@ class ReactionsController < ApplicationController def create @user = valid_user unless @user - render json: { message: "invalid_user" }, :status => 422 + render json: { message: "invalid_user" }, status: 422 return end Rails.cache.delete "count_for_reactable-#{params[:reactable_type]}-#{params[:reactable_id]}" diff --git a/app/controllers/api/v0/users_controller.rb b/app/controllers/api/v0/users_controller.rb index 72370e6592b91..d0ac961d751d2 100644 --- a/app/controllers/api/v0/users_controller.rb +++ b/app/controllers/api/v0/users_controller.rb @@ -16,11 +16,11 @@ def index end def show - if params[:id] == "by_username" - @user = User.find_by_username(params[:url]) - else - @user = User.find(params[:id]) - end + @user = if params[:id] == "by_username" + User.find_by_username(params[:url]) + else + User.find(params[:id]) + end end def less_than_one_day_old?(user) diff --git a/app/controllers/articles_controller.rb b/app/controllers/articles_controller.rb index 10eef72ccaf7d..53dc454bbc2a3 100644 --- a/app/controllers/articles_controller.rb +++ b/app/controllers/articles_controller.rb @@ -50,10 +50,10 @@ def new if params[:state] == "v2" || Rails.env.development? Article.new else - Article.new( - body_markdown: "---\ntitle: \npublished: false\ndescription: \ntags: \n---\n\n", - processed_html: "", - ) + Article.new( + body_markdown: "---\ntitle: \npublished: false\ndescription: \ntags: \n---\n\n", + processed_html: "", + ) end end end @@ -163,11 +163,7 @@ def create_or_update_job_opportunity end def set_article - owner = if User.find_by_username(params[:username]) - User.find_by_username(params[:username]) - else - Organization.find_by_slug(params[:username]) - end + owner = User.find_by_username(params[:username]) || Organization.find_by_slug(params[:username]) found_article = if params[:slug] owner.articles.includes(:user).find_by_slug(params[:slug]) else diff --git a/app/controllers/async_info_controller.rb b/app/controllers/async_info_controller.rb index 12f0f22d2b543..94a0c1f0bd0ae 100644 --- a/app/controllers/async_info_controller.rb +++ b/app/controllers/async_info_controller.rb @@ -6,8 +6,8 @@ def base_data flash.discard(:notice) unless user_signed_in? render json: { - param: request_forgery_protection_token, - token: form_authenticity_token, + param: request_forgery_protection_token, + token: form_authenticity_token, } return end @@ -22,7 +22,7 @@ def base_data render json: { param: request_forgery_protection_token, token: form_authenticity_token, - user: user_data.to_json + user: user_data.to_json, } end end @@ -36,7 +36,7 @@ def user_data username: @user.username, profile_image_90: ProfileImage.new(@user).get(90), followed_tag_names: @user.cached_followed_tag_names, - followed_tags: @user.cached_followed_tags.to_json(only: [:id,:name,:bg_color_hex,:text_color_hex]), + followed_tags: @user.cached_followed_tags.to_json(only: %i[id name bg_color_hex text_color_hex]), followed_user_ids: @user.cached_following_users_ids, reading_list_ids: ReadingList.new(@user).cached_ids_of_articles, saw_onboarding: @user.saw_onboarding, @@ -44,7 +44,7 @@ def user_data checked_code_of_conduct: @user.checked_code_of_conduct, number_of_comments: @user.comments.count, display_sponsors: @user.display_sponsors, - trusted: @user.trusted + trusted: @user.trusted, } end end diff --git a/app/controllers/blocks_controller.rb b/app/controllers/blocks_controller.rb index d6c91d3b654bf..f3640c4335338 100644 --- a/app/controllers/blocks_controller.rb +++ b/app/controllers/blocks_controller.rb @@ -1,9 +1,8 @@ class BlocksController < ApplicationController - before_action :set_block, only: [:show, :edit, :update, :destroy] + before_action :set_block, only: %i[show edit update destroy] after_action :verify_authorized - # GET /blocks # GET /blocks.json def index @@ -80,5 +79,4 @@ def destroy def set_block @block = Block.find(params[:id]) end - end diff --git a/app/controllers/chat_channel_memberships_controller.rb b/app/controllers/chat_channel_memberships_controller.rb index 3ce5388323d87..e5ec7fc0a7027 100644 --- a/app/controllers/chat_channel_memberships_controller.rb +++ b/app/controllers/chat_channel_memberships_controller.rb @@ -7,7 +7,7 @@ def create ChatChannelMembership.create( user_id: permitted_params[:user_id], chat_channel_id: @chat_channel.id, - status: "pending" + status: "pending", ) @chat_channel.index! end @@ -41,4 +41,4 @@ def destroy def permitted_params params.require(:chat_channel_membership).permit(:user_id, :chat_channel_id, :user_action, :id) end -end \ No newline at end of file +end diff --git a/app/controllers/chat_channels_controller.rb b/app/controllers/chat_channels_controller.rb index 98dd56a3303ab..a4acec8ac1361 100644 --- a/app/controllers/chat_channels_controller.rb +++ b/app/controllers/chat_channels_controller.rb @@ -24,7 +24,7 @@ def create authorize ChatChannel @chat_channel = ChatChannelCreationService.new(current_user, params[:chat_channel]).create if @chat_channel.valid? - render json: { status: "success", chat_channel: @chat_channel.to_json(only: [:channel_name,:slug]) }, status: 200 + render json: { status: "success", chat_channel: @chat_channel.to_json(only: %i[channel_name slug]) }, status: 200 else render json: { errors: @chat_channel.errors.full_messages } end @@ -35,7 +35,7 @@ def update authorize @chat_channel ChatChannelUpdateService.new(@chat_channel, chat_channel_params).update if @chat_channel.valid? - render json: { status: "success", chat_channel: @chat_channel.to_json(only: [:channel_name,:slug]) }, status: 200 + render json: { status: "success", chat_channel: @chat_channel.to_json(only: %i[channel_name slug]) }, status: 200 else render json: { errors: @chat_channel.errors.full_messages } end @@ -101,25 +101,24 @@ def render_unopened_json_response end def render_pending_json_response - if current_user - @chat_channels_memberships = current_user. - chat_channel_memberships.includes(:chat_channel). - where(status: "pending"). - order("chat_channel_memberships.updated_at DESC") - else - @chat_channels_memberships = [] - end + @chat_channels_memberships = if current_user + current_user. + chat_channel_memberships.includes(:chat_channel). + where(status: "pending"). + order("chat_channel_memberships.updated_at DESC") + else + [] + end render "index.json" end - def render_channels_html return unless current_user if params[:slug] - slug = if params[:slug] && params[:slug].start_with?("@") - [current_user.username, params[:slug].gsub("@", "")].sort.join("/") - else - params[:slug] + slug = if params[:slug]&.start_with?("@") + [current_user.username, params[:slug].gsub("@", "")].sort.join("/") + else + params[:slug] end @active_channel = ChatChannel.find_by_slug(slug) @active_channel.current_user = current_user if @active_channel @@ -130,9 +129,9 @@ def render_channels_html def generate_algolia_search_key current_user_id = current_user.id - params = {filters: "viewable_by:#{current_user_id} AND status: active"} + params = { filters: "viewable_by:#{current_user_id} AND status: active" } @secured_algolia_key = Algolia.generate_secured_api_key( - ApplicationConfig["ALGOLIASEARCH_SEARCH_ONLY_KEY"], params, + ApplicationConfig["ALGOLIASEARCH_SEARCH_ONLY_KEY"], params ) end diff --git a/app/controllers/dashboards_controller.rb b/app/controllers/dashboards_controller.rb index 04da56cf6e89f..d80176e2c23bf 100644 --- a/app/controllers/dashboards_controller.rb +++ b/app/controllers/dashboards_controller.rb @@ -16,7 +16,7 @@ def show elsif params[:which] == "user_followers" @follows = Follow.where(followable_id: @user.id, followable_type: "User"). includes(:follower).order("created_at DESC").limit(80) - elsif @user&.organization && @user.org_admin && params[:which] == "organization" + elsif @user&.organization && @user&.org_admin && params[:which] == "organization" @articles = @user.organization.articles.order("created_at DESC").decorate elsif @user @articles = @user.articles.order("created_at DESC").decorate diff --git a/app/controllers/followed_articles_controller.rb b/app/controllers/followed_articles_controller.rb index 5bad9c71b7228..99b00c9e1c9e5 100644 --- a/app/controllers/followed_articles_controller.rb +++ b/app/controllers/followed_articles_controller.rb @@ -2,8 +2,8 @@ class FollowedArticlesController < ApplicationController # No authorization required for entirely public controller caches_action :index, - :cache_path => Proc.new { "followed_articles_#{current_user.id}__#{current_user.updated_at}__#{user_signed_in?.to_s}" }, - :expires_in => 35.minutes + cache_path: Proc.new { "followed_articles_#{current_user.id}__#{current_user.updated_at}__#{user_signed_in?}" }, + expires_in: 35.minutes def index if current_user @@ -26,9 +26,9 @@ def index classic_article = Suggester::Articles::Classic.new(current_user).get response.headers["Cache-Control"] = "public, max-age=150" render json: { - articles: @articles, - classic_article: (article_json(classic_article) if classic_article), - }.to_json + articles: @articles, + classic_article: (article_json(classic_article) if classic_article), + }.to_json end def inappropriate_hiring_instance(article) diff --git a/app/controllers/github_repos_controller.rb b/app/controllers/github_repos_controller.rb index 1f52c522f6dec..21166e6790ebf 100644 --- a/app/controllers/github_repos_controller.rb +++ b/app/controllers/github_repos_controller.rb @@ -29,7 +29,7 @@ def update def create_octokit_client current_user_token = current_user.identities.where(provider: "github").last.token client = Octokit::Client.new(access_token: current_user_token) - client.repositories.sort_by!(&:name) if client + client&.repositories&.sort_by!(&:name) client end diff --git a/app/controllers/giveaways_controller.rb b/app/controllers/giveaways_controller.rb index e77ad854ec698..c772107f50c9f 100644 --- a/app/controllers/giveaways_controller.rb +++ b/app/controllers/giveaways_controller.rb @@ -56,57 +56,57 @@ def update end private - # Never trust parameters from the scary internet, only allow the white list through. - def user_params - accessible = [ - :email, - :shipping_name, - :shipping_company, - :shipping_address, - :shipping_address_line_2, - :shipping_city, - :shipping_state, - :shipping_country, - :shipping_postal_code, - :shipping_validated, - :top_languages, - :experience_level, - :specialty, - :tabs_or_spaces, - :onboarding_package_requested, - :onboarding_package_form_submmitted_at, - :personal_data_updated_at, - :shirt_size, - :shirt_gender, - ] - params.require(:user).permit(accessible) - end - def confirm_presence - unless user_params[:shipping_name].present? - @errors << "You need a shipping name" - @invalid_form = true - end - unless user_params[:shipping_address].present? - @errors << "You need a shipping address" - @invalid_form = true - end - unless user_params[:shipping_city].present? - @errors << "You need a shipping city" - @invalid_form = true - end - unless user_params[:shipping_country].present? - @errors << "You need a shipping country" - @invalid_form = true - end - unless user_params[:top_languages].present? - @errors << "You need to include your favorite languages. It's a spam filter." - @invalid_form = true - end + # Never trust parameters from the scary internet, only allow the white list through. + def user_params + accessible = %i[ + email + shipping_name + shipping_company + shipping_address + shipping_address_line_2 + shipping_city + shipping_state + shipping_country + shipping_postal_code + shipping_validated + top_languages + experience_level + specialty + tabs_or_spaces + onboarding_package_requested + onboarding_package_form_submmitted_at + personal_data_updated_at + shirt_size + shirt_gender + ] + params.require(:user).permit(accessible) + end + def confirm_presence + unless user_params[:shipping_name].present? + @errors << "You need a shipping name" + @invalid_form = true end - - def prevent_request_if_requested_twice - return if current_user.onboarding_package_requested_again + unless user_params[:shipping_address].present? + @errors << "You need a shipping address" + @invalid_form = true + end + unless user_params[:shipping_city].present? + @errors << "You need a shipping city" + @invalid_form = true + end + unless user_params[:shipping_country].present? + @errors << "You need a shipping country" + @invalid_form = true + end + unless user_params[:top_languages].present? + @errors << "You need to include your favorite languages. It's a spam filter." + @invalid_form = true end + end + + def prevent_request_if_requested_twice + return if current_user.onboarding_package_requested_again + end end diff --git a/app/controllers/image_uploads_controller.rb b/app/controllers/image_uploads_controller.rb index b8c69035cda78..e5af793f74c6e 100644 --- a/app/controllers/image_uploads_controller.rb +++ b/app/controllers/image_uploads_controller.rb @@ -6,10 +6,10 @@ def create authorize :image_upload uploader = ArticleImageUploader.new uploader.store!(params[:image]) - link = if params[:wrap_cloudinary] - ApplicationController.helpers.cloud_cover_url(uploader.url) - else - uploader.url + link = if params[:wrap_cloudinary] + ApplicationController.helpers.cloud_cover_url(uploader.url) + else + uploader.url end respond_to do |format| format.json { render json: { link: link }, status: 200 } diff --git a/app/controllers/internal/application_controller.rb b/app/controllers/internal/application_controller.rb index 1388af441a72d..5c12fbb62817d 100644 --- a/app/controllers/internal/application_controller.rb +++ b/app/controllers/internal/application_controller.rb @@ -1,9 +1,9 @@ class Internal::ApplicationController < ApplicationController - before_action :authorize_admin + before_action :authorize_admin - private + private - def authorize_admin - authorize :admin, :show? - end + def authorize_admin + authorize :admin, :show? + end end diff --git a/app/controllers/internal/articles_controller.rb b/app/controllers/internal/articles_controller.rb index 446f88c6f5f48..be7c6eee47f05 100644 --- a/app/controllers/internal/articles_controller.rb +++ b/app/controllers/internal/articles_controller.rb @@ -87,7 +87,7 @@ def index page(params[:page]). per(100). limited_columns_internal_select - else #MIX + else # MIX @articles = Article. where(published: true). order("published_at DESC"). diff --git a/app/controllers/internal/buffer_updates_controller.rb b/app/controllers/internal/buffer_updates_controller.rb index aef25399a970b..e34d2a071e54b 100644 --- a/app/controllers/internal/buffer_updates_controller.rb +++ b/app/controllers/internal/buffer_updates_controller.rb @@ -11,4 +11,4 @@ def create render body: nil end end -end \ No newline at end of file +end diff --git a/app/controllers/internal/comments_controller.rb b/app/controllers/internal/comments_controller.rb index f53902de4ee19..0afc0f3aeb4f9 100644 --- a/app/controllers/internal/comments_controller.rb +++ b/app/controllers/internal/comments_controller.rb @@ -1,22 +1,22 @@ class Internal::CommentsController < Internal::ApplicationController - layout 'internal' + layout "internal" def index - if params[:state]&.start_with?("toplast-") - @comments = Comment. - includes(:user). - includes(:commentable). - includes(:reactions). - order("positive_reactions_count DESC"). - where("created_at > ?", params[:state].split("-").last.to_i.days.ago). - page(params[:page] || 1).per(50) - else - @comments = Comment - .includes(:user) - .includes(:commentable) - .includes(:reactions) - .order("created_at DESC") - .page(params[:page] || 1).per(50) - end + @comments = if params[:state]&.start_with?("toplast-") + Comment. + includes(:user). + includes(:commentable). + includes(:reactions). + order("positive_reactions_count DESC"). + where("created_at > ?", params[:state].split("-").last.to_i.days.ago). + page(params[:page] || 1).per(50) + else + Comment. + includes(:user). + includes(:commentable). + includes(:reactions). + order("created_at DESC"). + page(params[:page] || 1).per(50) + end end end diff --git a/app/controllers/internal/dogfood_controller.rb b/app/controllers/internal/dogfood_controller.rb index 8552ebeba8f0e..2863678d8cad4 100644 --- a/app/controllers/internal/dogfood_controller.rb +++ b/app/controllers/internal/dogfood_controller.rb @@ -11,7 +11,7 @@ def index @team_members = User.where(username: usernames) @comments_this_week = Comment.where(user_id: @team_members.pluck(:id)).where("created_at > ?", Date.today.beginning_of_week).pluck(:user_id) @comment_totals_this_week = frequency(@comments_this_week) - @comments_24_hours = Comment.where(user_id: @team_members.pluck(:id)).where("created_at > ?",24.hours.ago).pluck(:user_id) + @comments_24_hours = Comment.where(user_id: @team_members.pluck(:id)).where("created_at > ?", 24.hours.ago).pluck(:user_id) @comment_totals_24_hours = frequency(@comments_24_hours) end @@ -22,5 +22,4 @@ def frequency(a) { number_of_comments: values.size, username: User.find(key).username } end.sort_by { |hsh| hsh[:number_of_comments] }.reverse! end - end diff --git a/app/controllers/internal/feedback_messages_controller.rb b/app/controllers/internal/feedback_messages_controller.rb index 21ef95195bfa0..693b1ac5bb05f 100644 --- a/app/controllers/internal/feedback_messages_controller.rb +++ b/app/controllers/internal/feedback_messages_controller.rb @@ -31,7 +31,7 @@ def update def feedback_message_params params[:feedback_message].permit( :status, :reviewer_id, - note: [:content, :reason], + note: %i[content reason] ) end end diff --git a/app/controllers/internal/tags_controller.rb b/app/controllers/internal/tags_controller.rb index 91c945f4efa7b..c83372f57bdc3 100644 --- a/app/controllers/internal/tags_controller.rb +++ b/app/controllers/internal/tags_controller.rb @@ -1,21 +1,21 @@ class Internal::TagsController < Internal::ApplicationController - layout 'internal' + layout "internal" def index - if params[:state] == "supported" - @tags = Tag.where(supported: true).order("taggings_count DESC").limit(120) - elsif params[:state] == "unsupported" - @tags = Tag.where(supported: false).order("taggings_count DESC").limit(120) - else - @tags = Tag.order("taggings_count DESC").limit(120) - end + @tags = if params[:state] == "supported" + Tag.where(supported: true).order("taggings_count DESC").limit(120) + elsif params[:state] == "unsupported" + Tag.where(supported: false).order("taggings_count DESC").limit(120) + else + Tag.order("taggings_count DESC").limit(120) + end end def update @tag = Tag.find(params[:id]) @tag.update!(tag_params) redirect_to(action: :index) - end + end private @@ -27,5 +27,4 @@ def tag_params :bg_color_hex, :text_color_hex) end - -end \ No newline at end of file +end diff --git a/app/controllers/internal/users_controller.rb b/app/controllers/internal/users_controller.rb index aecbd9053f930..8290a5fb1e517 100644 --- a/app/controllers/internal/users_controller.rb +++ b/app/controllers/internal/users_controller.rb @@ -1,5 +1,5 @@ class Internal::UsersController < Internal::ApplicationController - layout 'internal' + layout "internal" def index @users = User.where.not(feed_url: nil) @@ -52,7 +52,7 @@ def strip_user(user) user.remove_from_index! user.save! user.update!(old_username: nil) - rescue => e + rescue StandardError => e flash[:error] = e.message end end diff --git a/app/controllers/messages_controller.rb b/app/controllers/messages_controller.rb index f46eeff0164ff..620a7b8124caf 100644 --- a/app/controllers/messages_controller.rb +++ b/app/controllers/messages_controller.rb @@ -49,7 +49,7 @@ def create_pusher_payload(new_message) message: new_message.message_html, timestamp: Time.now, color: new_message.preferred_user_color, - reception_method: "pushed" + reception_method: "pushed", }.to_json end diff --git a/app/controllers/notifications/reads_controller.rb b/app/controllers/notifications/reads_controller.rb index a905fd0c784c0..7cbb10bb99d7a 100644 --- a/app/controllers/notifications/reads_controller.rb +++ b/app/controllers/notifications/reads_controller.rb @@ -1,5 +1,4 @@ class Notifications::ReadsController < ApplicationController - def create result = "" result = ReadNotificationsService.new(current_user).mark_as_read if current_user diff --git a/app/controllers/notifications_controller.rb b/app/controllers/notifications_controller.rb index 9b71d9de1c72e..051e69fc06e22 100644 --- a/app/controllers/notifications_controller.rb +++ b/app/controllers/notifications_controller.rb @@ -65,4 +65,4 @@ def construct_query(model, ids) end end end -end \ No newline at end of file +end diff --git a/app/controllers/pages_controller.rb b/app/controllers/pages_controller.rb index 9012e5b3170de..0912274bd8be4 100644 --- a/app/controllers/pages_controller.rb +++ b/app/controllers/pages_controller.rb @@ -1,6 +1,6 @@ class PagesController < ApplicationController # No authorization required for entirely public controller - before_action :set_cache_control_headers, only: [:rlyweb, :now, :events, :membership, :survey] + before_action :set_cache_control_headers, only: %i[rlyweb now events membership survey] def now set_surrogate_key_header "now_page" @@ -49,7 +49,8 @@ def welcome def live @active_channel = ChatChannel.find_by_channel_name("Workshop") @chat_channels = [@active_channel].to_json( - only: [:channel_name,:channel_type,:last_message_at,:slug, :status, :id]) + only: %i[channel_name channel_type last_message_at slug status id], + ) end private # helpers diff --git a/app/controllers/podcast_episodes_controller.rb b/app/controllers/podcast_episodes_controller.rb index 1fd943f9188f2..9191c016779e0 100644 --- a/app/controllers/podcast_episodes_controller.rb +++ b/app/controllers/podcast_episodes_controller.rb @@ -7,13 +7,13 @@ def index @podcasts = Podcast.order("title asc") @podcast_episodes = PodcastEpisode.order("published_at desc").first(20) unless params[:q].present? - set_surrogate_key_header 'podcast_episodes_all '+params[:q].to_s, @podcast_episodes.map { |e| e["record_key"]} + set_surrogate_key_header "podcast_episodes_all " + params[:q].to_s, @podcast_episodes.map { |e| e["record_key"] } end @featured_story = Article.new @podcast_index = true @article_index = true @list_of = "podcast-episodes" - render :template => 'articles/index' + render template: "articles/index" end private @@ -26,7 +26,4 @@ def podcast_episode_params :remote_social_image_url, :quote) end - - - end diff --git a/app/controllers/pusher_controller.rb b/app/controllers/pusher_controller.rb index 0cf437dda1f60..de9ffca070543 100644 --- a/app/controllers/pusher_controller.rb +++ b/app/controllers/pusher_controller.rb @@ -1,13 +1,11 @@ class PusherController < ApplicationController - def auth if valid_channel - response = Pusher.authenticate(params[:channel_name], params[:socket_id], { - user_id: current_user.id, # => required - }) + response = Pusher.authenticate(params[:channel_name], params[:socket_id], + user_id: current_user.id) # => required render json: response else - render json: { text: 'Forbidden', status: '403' } + render json: { text: "Forbidden", status: "403" } end end diff --git a/app/controllers/reactions_controller.rb b/app/controllers/reactions_controller.rb index ad85a697c6183..9c71265f9ed48 100644 --- a/app/controllers/reactions_controller.rb +++ b/app/controllers/reactions_controller.rb @@ -18,13 +18,13 @@ def index { current_user: { id: efficient_current_user_id }, article_reaction_counts: Reaction.count_for_reactable(article), - reactions: reactions + reactions: reactions, }.to_json else comments = Comment.where( commentable_id: params[:commentable_id], commentable_type: params[:commentable_type], - ).select([:id, :positive_reactions_count]) + ).select(%i[id positive_reactions_count]) comment_ids = comments.map(&:id) reaction_counts = comments.map { |c| { id: c.id, count: c.positive_reactions_count } } reactions = current_user ? cached_user_positive_reactions(current_user).where(reactable_id: comment_ids) : [] @@ -32,7 +32,7 @@ def index { current_user: { id: current_user&.id }, positive_reaction_counts: reaction_counts, - reactions: reactions + reactions: reactions, }.to_json end set_surrogate_key_header params.to_s unless current_user @@ -66,7 +66,7 @@ def create def cached_user_positive_reactions(user) Rails.cache.fetch("cached_user_reactions-#{user.id}-#{user.updated_at}", expires_in: 24.hours) do Reaction.where(user_id: user.id). - where("points > ?", 0) + where("points > ?", 0) end end end diff --git a/app/controllers/registrations_controller.rb b/app/controllers/registrations_controller.rb index bf8b235bf810a..a4660eccdb754 100644 --- a/app/controllers/registrations_controller.rb +++ b/app/controllers/registrations_controller.rb @@ -1,5 +1,5 @@ class RegistrationsController < Devise::RegistrationsController - prepend_before_action :require_no_authentication, :only => [] + prepend_before_action :require_no_authentication, only: [] # No authorization required for public registration route def new diff --git a/app/controllers/stories_controller.rb b/app/controllers/stories_controller.rb index 7484d6907cb15..bb633ca82e261 100644 --- a/app/controllers/stories_controller.rb +++ b/app/controllers/stories_controller.rb @@ -1,6 +1,6 @@ class StoriesController < ApplicationController - before_action :authenticate_user!, except: [:index,:search,:show, :feed, :new] - before_action :set_cache_control_headers, only: [:index, :search, :show] + before_action :authenticate_user!, except: %i[index search show feed new] + before_action :set_cache_control_headers, only: %i[index search show] def index return handle_user_or_organization_or_podcast_index if params[:username] @@ -81,11 +81,11 @@ def handle_tag_index @stories = article_finder(8) - if @tag_model && @tag_model.requires_approval + if @tag_model&.requires_approval @stories = @stories.where(approved: true) end - @stories = stories_by_timeframe + @stories = stories_by_timeframe @stories = @stories.decorate @featured_story = Article.new @@ -147,7 +147,7 @@ def handle_organization_index end def handle_user_index - @user = User.find_by_username(params[:username].tr("@","").downcase) + @user = User.find_by_username(params[:username].tr("@", "").downcase) unless @user redirect_to_changed_username_profile return @@ -173,7 +173,7 @@ def handle_podcast_show @comments_to_show_count = 25 @comment = Comment.new render template: "podcast_episodes/show" - return + nil end def redirect_if_view_param @@ -239,7 +239,7 @@ def handle_possible_redirect def assign_organization_article @article = @organization.articles.find_by_slug(params[:slug])&.decorate - @user = @article&.user || not_found #The org may have changed back to user and this does not handle that properly + @user = @article&.user || not_found # The org may have changed back to user and this does not handle that properly end def assign_user_article @@ -273,12 +273,12 @@ def assign_podcasts def article_finder(num_articles) Article.where(published: true). - includes(:user). - limited_column_select. - page(@page). - per(num_articles). - filter_excluded_tags(params[:tag]) - end + includes(:user). + limited_column_select. + page(@page). + per(num_articles). + filter_excluded_tags(params[:tag]) + end def assign_sticky_nav return unless @article @@ -298,7 +298,7 @@ def assign_sticky_nav order("RANDOM()"). limit(8) if tag_articles.size < 6 - more_articles = Article.tagged_with((["career","productivity","discuss","explainlikeimfive"]), any: true). + more_articles = Article.tagged_with(["career", "productivity", "discuss", "explainlikeimfive"], any: true). includes(:user). where("comments_count > ?", comment_count_num). limited_column_select. @@ -310,12 +310,11 @@ def assign_sticky_nav end @user_stickies = (@organization || @user).articles. - where(published: true). - limited_column_select. - tagged_with(article_tags, any: true). - where.not(id: @article.id).order("published_at DESC"). - limit(2) + where(published: true). + limited_column_select. + tagged_with(article_tags, any: true). + where.not(id: @article.id).order("published_at DESC"). + limit(2) @sticky_articles = (tag_articles + more_articles).sample(8) end - -end \ No newline at end of file +end diff --git a/app/controllers/twilio_tokens_controller.rb b/app/controllers/twilio_tokens_controller.rb index 1c7296d7989db..b9b6499691834 100644 --- a/app/controllers/twilio_tokens_controller.rb +++ b/app/controllers/twilio_tokens_controller.rb @@ -9,7 +9,7 @@ def show return end @chat_channel = ChatChannel.find(video_channel.to_i) - authorize @chat_channel #show pundit method for chat_channel_policy works here, should always check though + authorize @chat_channel # show pundit method for chat_channel_policy works here, should always check though @twilio_token = TwilioToken.new(current_user, params[:id]).get render json: { status: "success", token: @twilio_token }, status: 200 end diff --git a/app/controllers/videos_controller.rb b/app/controllers/videos_controller.rb index d60f10024053c..f06d43d4a6969 100644 --- a/app/controllers/videos_controller.rb +++ b/app/controllers/videos_controller.rb @@ -7,7 +7,7 @@ def new def create authorize :video - @article = Article.new(body_markdown:"---\ntitle: Unpublished Video ~ #{rand(100000).to_s(26)}\npublished: false\ndescription: \ntags: \n---\n\n",processed_html:"") + @article = Article.new(body_markdown: "---\ntitle: Unpublished Video ~ #{rand(100000).to_s(26)}\npublished: false\ndescription: \ntags: \n---\n\n", processed_html: "") @article.user_id = current_user.id @article.show_comments = true assign_video_attributes diff --git a/app/dashboards/article_dashboard.rb b/app/dashboards/article_dashboard.rb index 7ec657560e15e..bb3b2896f9a84 100644 --- a/app/dashboards/article_dashboard.rb +++ b/app/dashboards/article_dashboard.rb @@ -45,20 +45,20 @@ class ArticleDashboard < Administrate::BaseDashboard video_thumbnail_url: Field::String, video_closed_caption_track_url: Field::String, main_tag_name_for_social: Field::String, - } + }.freeze # COLLECTION_ATTRIBUTES # an array of attributes that will be displayed on the model's index page. # # By default, it's limited to four items to reduce clutter on index pages. # Feel free to add, remove, or rearrange items. - COLLECTION_ATTRIBUTES = [ - :user, - :title, - :published, - :featured, - :comments - ] + COLLECTION_ATTRIBUTES = %i[ + user + title + published + featured + comments + ].freeze # SHOW_PAGE_ATTRIBUTES # an array of attributes that will be displayed on the model's show page. @@ -67,35 +67,34 @@ class ArticleDashboard < Administrate::BaseDashboard # FORM_ATTRIBUTES # an array of attributes that will be displayed # on the model's form (`new` and `edit`) pages. - FORM_ATTRIBUTES = [ - :user_id, - :second_user_id, - :third_user_id, - :organization, - :title, - :body_markdown, - :slug, - :social_image, - :featured, - :approved, - :featured_number, - :canonical_url, - :password, - :published_at, - :collection, - :collection_position, - :name_within_collection, - :show_comments, - :main_image_background_hex_color, - :ids_for_suggested_articles, - :video, - :video_code, - :video_source_url, - :video_thumbnail_url, - :video_closed_caption_track_url, - :main_tag_name_for_social - - ] + FORM_ATTRIBUTES = %i[ + user_id + second_user_id + third_user_id + organization + title + body_markdown + slug + social_image + featured + approved + featured_number + canonical_url + password + published_at + collection + collection_position + name_within_collection + show_comments + main_image_background_hex_color + ids_for_suggested_articles + video + video_code + video_source_url + video_thumbnail_url + video_closed_caption_track_url + main_tag_name_for_social + ].freeze # Overwrite this method to customize how articles are displayed # across all pages of the admin dashboard. diff --git a/app/dashboards/badge_achievement_dashboard.rb b/app/dashboards/badge_achievement_dashboard.rb index 477227c96f5a8..0b946ffd85a29 100644 --- a/app/dashboards/badge_achievement_dashboard.rb +++ b/app/dashboards/badge_achievement_dashboard.rb @@ -26,34 +26,34 @@ class BadgeAchievementDashboard < Administrate::BaseDashboard # # By default, it's limited to four items to reduce clutter on index pages. # Feel free to add, remove, or rearrange items. - COLLECTION_ATTRIBUTES = [ - :user, - :badge, - :rewarder, - :id, + COLLECTION_ATTRIBUTES = %i[ + user + badge + rewarder + id ].freeze # SHOW_PAGE_ATTRIBUTES # an array of attributes that will be displayed on the model's show page. - SHOW_PAGE_ATTRIBUTES = [ - :id, - :user, - :name_of_user, - :badge, - :rewarding_context_message, - :rewarder, - :created_at, - :updated_at, + SHOW_PAGE_ATTRIBUTES = %i[ + id + user + name_of_user + badge + rewarding_context_message + rewarder + created_at + updated_at ].freeze # FORM_ATTRIBUTES # an array of attributes that will be displayed # on the model's form (`new` and `edit`) pages. - FORM_ATTRIBUTES = [ - :user_id, - :rewarding_context_message_markdown, - :badge, - :rewarder_id, + FORM_ATTRIBUTES = %i[ + user_id + rewarding_context_message_markdown + badge + rewarder_id ].freeze # Overwrite this method to customize how badge achievements are displayed diff --git a/app/dashboards/badge_dashboard.rb b/app/dashboards/badge_dashboard.rb index 80ccac5a1d1ff..cc9090a6e877e 100644 --- a/app/dashboards/badge_dashboard.rb +++ b/app/dashboards/badge_dashboard.rb @@ -23,35 +23,35 @@ class BadgeDashboard < Administrate::BaseDashboard # # By default, it's limited to four items to reduce clutter on index pages. # Feel free to add, remove, or rearrange items. - COLLECTION_ATTRIBUTES = [ - :badge_image, - :id, - :title, - :slug, - :description, + COLLECTION_ATTRIBUTES = %i[ + badge_image + id + title + slug + description ].freeze # SHOW_PAGE_ATTRIBUTES # an array of attributes that will be displayed on the model's show page. - SHOW_PAGE_ATTRIBUTES = [ - :users, - :id, - :title, - :slug, - :description, - :badge_image, - :created_at, - :updated_at, + SHOW_PAGE_ATTRIBUTES = %i[ + users + id + title + slug + description + badge_image + created_at + updated_at ].freeze # FORM_ATTRIBUTES # an array of attributes that will be displayed # on the model's form (`new` and `edit`) pages. - FORM_ATTRIBUTES = [ - :title, - :slug, - :description, - :badge_image, + FORM_ATTRIBUTES = %i[ + title + slug + description + badge_image ].freeze # Overwrite this method to customize how badges are displayed diff --git a/app/dashboards/collection_dashboard.rb b/app/dashboards/collection_dashboard.rb index 567d2d285c3cd..18c5e19af2592 100644 --- a/app/dashboards/collection_dashboard.rb +++ b/app/dashboards/collection_dashboard.rb @@ -20,51 +20,51 @@ class CollectionDashboard < Administrate::BaseDashboard published: Field::Boolean, created_at: Field::DateTime, updated_at: Field::DateTime, - } + }.freeze # COLLECTION_ATTRIBUTES # an array of attributes that will be displayed on the model's index page. # # By default, it's limited to four items to reduce clutter on index pages. # Feel free to add, remove, or rearrange items. - COLLECTION_ATTRIBUTES = [ - :articles, - :user, - :organization, - :id, - ] + COLLECTION_ATTRIBUTES = %i[ + articles + user + organization + id + ].freeze # SHOW_PAGE_ATTRIBUTES # an array of attributes that will be displayed on the model's show page. - SHOW_PAGE_ATTRIBUTES = [ - :articles, - :user, - :organization, - :id, - :title, - :slug, - :description, - :main_image, - :social_image, - :published, - :created_at, - :updated_at, - ] + SHOW_PAGE_ATTRIBUTES = %i[ + articles + user + organization + id + title + slug + description + main_image + social_image + published + created_at + updated_at + ].freeze # FORM_ATTRIBUTES # an array of attributes that will be displayed # on the model's form (`new` and `edit`) pages. - FORM_ATTRIBUTES = [ - :articles, - :user, - :organization, - :title, - :slug, - :description, - :main_image, - :social_image, - :published, - ] + FORM_ATTRIBUTES = %i[ + articles + user + organization + title + slug + description + main_image + social_image + published + ].freeze # Overwrite this method to customize how collections are displayed # across all pages of the admin dashboard. diff --git a/app/dashboards/comment_dashboard.rb b/app/dashboards/comment_dashboard.rb index 119de9a135b8f..cd41a7b87cea3 100644 --- a/app/dashboards/comment_dashboard.rb +++ b/app/dashboards/comment_dashboard.rb @@ -23,46 +23,46 @@ class CommentDashboard < Administrate::BaseDashboard id_code: Field::String, score: Field::Number, deleted: Field::Boolean, - } + }.freeze # COLLECTION_ATTRIBUTES # an array of attributes that will be displayed on the model's index page. # # By default, it's limited to four items to reduce clutter on index pages. # Feel free to add, remove, or rearrange items. - COLLECTION_ATTRIBUTES = [ - :id, - :name_of_user, - :body_markdown, - :reactions, - ] + COLLECTION_ATTRIBUTES = %i[ + id + name_of_user + body_markdown + reactions + ].freeze # SHOW_PAGE_ATTRIBUTES # an array of attributes that will be displayed on the model's show page. - SHOW_PAGE_ATTRIBUTES = [ - :commentable, - :user, - :name_of_user, - :reactions, - :id, - :body_markdown, - :edited, - :created_at, - :updated_at, - :ancestry, - :id_code, - :score, - :deleted, - ] + SHOW_PAGE_ATTRIBUTES = %i[ + commentable + user + name_of_user + reactions + id + body_markdown + edited + created_at + updated_at + ancestry + id_code + score + deleted + ].freeze # FORM_ATTRIBUTES # an array of attributes that will be displayed # on the model's form (`new` and `edit`) pages. - FORM_ATTRIBUTES = [ - :user_id, - :body_markdown, - :deleted, - ] + FORM_ATTRIBUTES = %i[ + user_id + body_markdown + deleted + ].freeze # Overwrite this method to customize how comments are displayed # across all pages of the admin dashboard. diff --git a/app/dashboards/dashboard_manifest.rb b/app/dashboards/dashboard_manifest.rb index 097e2d1a53789..37bb7fe121b6a 100644 --- a/app/dashboards/dashboard_manifest.rb +++ b/app/dashboards/dashboard_manifest.rb @@ -9,23 +9,23 @@ class DashboardManifest # To show or hide dashboards, add or remove the model name from this list. # Dashboards returned from this method must be Rails models for Administrate # to work correctly. - DASHBOARDS = [ - :articles, - :users, - :organizations, - :comments, - :follows, - :reactions, - :podcasts, - :podcast_episodes, - :collections, - :tags, - :email_messages, - :feedback_messages, - :display_ads, - :badges, - :badge_achievements, - ] + DASHBOARDS = %i[ + articles + users + organizations + comments + follows + reactions + podcasts + podcast_episodes + collections + tags + email_messages + feedback_messages + display_ads + badges + badge_achievements + ].freeze # DASHBOARDS = [ # :users, # :articles, diff --git a/app/dashboards/display_ad_dashboard.rb b/app/dashboards/display_ad_dashboard.rb index eb22c2894b3a8..9f3dc28e1ad11 100644 --- a/app/dashboards/display_ad_dashboard.rb +++ b/app/dashboards/display_ad_dashboard.rb @@ -28,42 +28,42 @@ class DisplayAdDashboard < Administrate::BaseDashboard # # By default, it's limited to four items to reduce clutter on index pages. # Feel free to add, remove, or rearrange items. - COLLECTION_ATTRIBUTES = [ - :organization, - :id, - :placement_area, - :body_markdown, + COLLECTION_ATTRIBUTES = %i[ + organization + id + placement_area + body_markdown ].freeze # SHOW_PAGE_ATTRIBUTES # an array of attributes that will be displayed on the model's show page. - SHOW_PAGE_ATTRIBUTES = [ - :organization, - :id, - :placement_area, - :body_markdown, - :processed_html, - :cost_per_impression, - :cost_per_click, - :impressions_count, - :clicks_count, - :published, - :approved, - :created_at, - :updated_at, + SHOW_PAGE_ATTRIBUTES = %i[ + organization + id + placement_area + body_markdown + processed_html + cost_per_impression + cost_per_click + impressions_count + clicks_count + published + approved + created_at + updated_at ].freeze # FORM_ATTRIBUTES # an array of attributes that will be displayed # on the model's form (`new` and `edit`) pages. - FORM_ATTRIBUTES = [ - :organization, - :placement_area, - :body_markdown, - :cost_per_impression, - :cost_per_click, - :published, - :approved, + FORM_ATTRIBUTES = %i[ + organization + placement_area + body_markdown + cost_per_impression + cost_per_click + published + approved ].freeze # Overwrite this method to customize how display ads are displayed diff --git a/app/dashboards/email_message_dashboard.rb b/app/dashboards/email_message_dashboard.rb index a717239f009ac..10ec447063643 100644 --- a/app/dashboards/email_message_dashboard.rb +++ b/app/dashboards/email_message_dashboard.rb @@ -30,32 +30,32 @@ class EmailMessageDashboard < Administrate::BaseDashboard # # By default, it's limited to four items to reduce clutter on index pages. # Feel free to add, remove, or rearrange items. - COLLECTION_ATTRIBUTES = [ - :user, - :id, - :subject, - :opened_at, - :clicked_at, + COLLECTION_ATTRIBUTES = %i[ + user + id + subject + opened_at + clicked_at ].freeze # SHOW_PAGE_ATTRIBUTES # an array of attributes that will be displayed on the model's show page. - SHOW_PAGE_ATTRIBUTES = [ - :user, - :id, - :token, - :to, - :mailer, - :subject, - :content, - :utm_source, - :utm_medium, - :utm_term, - :utm_content, - :utm_campaign, - :sent_at, - :opened_at, - :clicked_at, + SHOW_PAGE_ATTRIBUTES = %i[ + user + id + token + to + mailer + subject + content + utm_source + utm_medium + utm_term + utm_content + utm_campaign + sent_at + opened_at + clicked_at ].freeze # FORM_ATTRIBUTES diff --git a/app/dashboards/feedback_message_dashboard.rb b/app/dashboards/feedback_message_dashboard.rb index b67e792eaa20e..03832061a7995 100644 --- a/app/dashboards/feedback_message_dashboard.rb +++ b/app/dashboards/feedback_message_dashboard.rb @@ -20,31 +20,31 @@ class FeedbackMessageDashboard < Administrate::BaseDashboard # # By default, it's limited to four items to reduce clutter on index pages. # Feel free to add, remove, or rearrange items. - COLLECTION_ATTRIBUTES = [ - :user, - :id, - :message, - :feedback_type, + COLLECTION_ATTRIBUTES = %i[ + user + id + message + feedback_type ].freeze # SHOW_PAGE_ATTRIBUTES # an array of attributes that will be displayed on the model's show page. - SHOW_PAGE_ATTRIBUTES = [ - :user, - :id, - :message, - :feedback_type, - :category, + SHOW_PAGE_ATTRIBUTES = %i[ + user + id + message + feedback_type + category ].freeze # FORM_ATTRIBUTES # an array of attributes that will be displayed # on the model's form (`new` and `edit`) pages. - FORM_ATTRIBUTES = [ - :user, - :message, - :feedback_type, - :category, + FORM_ATTRIBUTES = %i[ + user + message + feedback_type + category ].freeze # Overwrite this method to customize how feedback messages are displayed diff --git a/app/dashboards/follow_dashboard.rb b/app/dashboards/follow_dashboard.rb index 0fb57b4fc92cf..b56423660a0a2 100644 --- a/app/dashboards/follow_dashboard.rb +++ b/app/dashboards/follow_dashboard.rb @@ -23,32 +23,32 @@ class FollowDashboard < Administrate::BaseDashboard # # By default, it's limited to four items to reduce clutter on index pages. # Feel free to add, remove, or rearrange items. - COLLECTION_ATTRIBUTES = [ - :created_at, - :followable_type, - :follower, - :blocked, + COLLECTION_ATTRIBUTES = %i[ + created_at + followable_type + follower + blocked ].freeze # SHOW_PAGE_ATTRIBUTES # an array of attributes that will be displayed on the model's show page. - SHOW_PAGE_ATTRIBUTES = [ - :followable_type, - :followable_id, - :follower, - :id, - :blocked, - :created_at, - :updated_at, + SHOW_PAGE_ATTRIBUTES = %i[ + followable_type + followable_id + follower + id + blocked + created_at + updated_at ].freeze # FORM_ATTRIBUTES # an array of attributes that will be displayed # on the model's form (`new` and `edit`) pages. - FORM_ATTRIBUTES = [ - :followable_id, - :follower, - :blocked, + FORM_ATTRIBUTES = %i[ + followable_id + follower + blocked ].freeze # Overwrite this method to customize how follows are displayed diff --git a/app/dashboards/organization_dashboard.rb b/app/dashboards/organization_dashboard.rb index db3a906d795a0..aa4cd5513d67f 100644 --- a/app/dashboards/organization_dashboard.rb +++ b/app/dashboards/organization_dashboard.rb @@ -34,20 +34,20 @@ class OrganizationDashboard < Administrate::BaseDashboard cta_button_text: Field::String, cta_button_url: Field::String, cta_body_markdown: Field::Text, - } + }.freeze # COLLECTION_ATTRIBUTES # an array of attributes that will be displayed on the model's index page. # # By default, it's limited to four items to reduce clutter on index pages. # Feel free to add, remove, or rearrange items. - COLLECTION_ATTRIBUTES = [ - :profile_image, - :name, - :url, - :twitter_username, - :approved, - ] + COLLECTION_ATTRIBUTES = %i[ + profile_image + name + url + twitter_username + approved + ].freeze # SHOW_PAGE_ATTRIBUTES # an array of attributes that will be displayed on the model's show page. @@ -56,30 +56,30 @@ class OrganizationDashboard < Administrate::BaseDashboard # FORM_ATTRIBUTES # an array of attributes that will be displayed # on the model's form (`new` and `edit`) pages. - FORM_ATTRIBUTES = [ - :name, - :slug, - :summary, - :tag_line, - :profile_image, - :nav_image, - :url, - :bg_color_hex, - :text_color_hex, - :twitter_username, - :github_username, - :jobs_url, - :jobs_email, - :address, - :city, - :state, - :zip_code, - :country, - :approved, - :cta_button_text, - :cta_button_url, - :cta_body_markdown, - ] + FORM_ATTRIBUTES = %i[ + name + slug + summary + tag_line + profile_image + nav_image + url + bg_color_hex + text_color_hex + twitter_username + github_username + jobs_url + jobs_email + address + city + state + zip_code + country + approved + cta_button_text + cta_button_url + cta_body_markdown + ].freeze def display_resource(organization) organization.name diff --git a/app/dashboards/podcast_dashboard.rb b/app/dashboards/podcast_dashboard.rb index 57437f6b15731..334c393c665a0 100644 --- a/app/dashboards/podcast_dashboard.rb +++ b/app/dashboards/podcast_dashboard.rb @@ -26,63 +26,63 @@ class PodcastDashboard < Administrate::BaseDashboard status_notice: Field::Text, created_at: Field::DateTime, updated_at: Field::DateTime, - } + }.freeze # COLLECTION_ATTRIBUTES # an array of attributes that will be displayed on the model's index page. # # By default, it's limited to four items to reduce clutter on index pages. # Feel free to add, remove, or rearrange items. - COLLECTION_ATTRIBUTES = [ - :podcast_episodes, - :id, - :title, - :description, - ] + COLLECTION_ATTRIBUTES = %i[ + podcast_episodes + id + title + description + ].freeze # SHOW_PAGE_ATTRIBUTES # an array of attributes that will be displayed on the model's show page. - SHOW_PAGE_ATTRIBUTES = [ - :podcast_episodes, - :id, - :title, - :description, - :feed_url, - :itunes_url, - :overcast_url, - :android_url, - :soundcloud_url, - :website_url, - :status_notice, - :twitter_username, - :main_color_hex, - :image, - :pattern_image, - :slug, - :created_at, - :updated_at, - ] + SHOW_PAGE_ATTRIBUTES = %i[ + podcast_episodes + id + title + description + feed_url + itunes_url + overcast_url + android_url + soundcloud_url + website_url + status_notice + twitter_username + main_color_hex + image + pattern_image + slug + created_at + updated_at + ].freeze # FORM_ATTRIBUTES # an array of attributes that will be displayed # on the model's form (`new` and `edit`) pages. - FORM_ATTRIBUTES = [ - :podcast_episodes, - :title, - :description, - :status_notice, - :feed_url, - :itunes_url, - :overcast_url, - :android_url, - :soundcloud_url, - :website_url, - :twitter_username, - :pattern_image, - :main_color_hex, - :image, - :slug, - ] + FORM_ATTRIBUTES = %i[ + podcast_episodes + title + description + status_notice + feed_url + itunes_url + overcast_url + android_url + soundcloud_url + website_url + twitter_username + pattern_image + main_color_hex + image + slug + ].freeze # Overwrite this method to customize how podcasts are displayed # across all pages of the admin dashboard. diff --git a/app/dashboards/podcast_episode_dashboard.rb b/app/dashboards/podcast_episode_dashboard.rb index 23e3c7d0c2dbe..54a69b7a6c2d5 100644 --- a/app/dashboards/podcast_episode_dashboard.rb +++ b/app/dashboards/podcast_episode_dashboard.rb @@ -32,52 +32,52 @@ class PodcastEpisodeDashboard < Administrate::BaseDashboard created_at: Field::DateTime, updated_at: Field::DateTime, social_image: CarrierwaveField, - } + }.freeze # COLLECTION_ATTRIBUTES # an array of attributes that will be displayed on the model's index page. # # By default, it's limited to four items to reduce clutter on index pages. # Feel free to add, remove, or rearrange items. - COLLECTION_ATTRIBUTES = [ - :id, - :title, - ] + COLLECTION_ATTRIBUTES = %i[ + id + title + ].freeze # SHOW_PAGE_ATTRIBUTES # an array of attributes that will be displayed on the model's show page. - SHOW_PAGE_ATTRIBUTES = [ - :id, - :podcast, - :title, - :image, - :social_image, - :body, - :featured, - :featured_number, - :media_url, - :website_url, - :itunes_url, - :duration_in_seconds, - :published_at, - :slug, - :created_at, - :updated_at, - ] + SHOW_PAGE_ATTRIBUTES = %i[ + id + podcast + title + image + social_image + body + featured + featured_number + media_url + website_url + itunes_url + duration_in_seconds + published_at + slug + created_at + updated_at + ].freeze # FORM_ATTRIBUTES # an array of attributes that will be displayed # on the model's form (`new` and `edit`) pages. - FORM_ATTRIBUTES = [ - :title, - :body, - :website_url, - :media_url, - :itunes_url, - :social_image, - :duration_in_seconds, - :published_at, - ] + FORM_ATTRIBUTES = %i[ + title + body + website_url + media_url + itunes_url + social_image + duration_in_seconds + published_at + ].freeze # Overwrite this method to customize how podcast episodes are displayed # across all pages of the admin dashboard. diff --git a/app/dashboards/reaction_dashboard.rb b/app/dashboards/reaction_dashboard.rb index 33c19c149569b..4c50002f0cb53 100644 --- a/app/dashboards/reaction_dashboard.rb +++ b/app/dashboards/reaction_dashboard.rb @@ -23,34 +23,34 @@ class ReactionDashboard < Administrate::BaseDashboard # # By default, it's limited to four items to reduce clutter on index pages. # Feel free to add, remove, or rearrange items. - COLLECTION_ATTRIBUTES = [ - :reactable, - :user, - :id, - :category, + COLLECTION_ATTRIBUTES = %i[ + reactable + user + id + category ].freeze # SHOW_PAGE_ATTRIBUTES # an array of attributes that will be displayed on the model's show page. - SHOW_PAGE_ATTRIBUTES = [ - :reactable, - :user, - :user_id, - :id, - :category, - :points, - :created_at, - :updated_at, + SHOW_PAGE_ATTRIBUTES = %i[ + reactable + user + user_id + id + category + points + created_at + updated_at ].freeze # FORM_ATTRIBUTES # an array of attributes that will be displayed # on the model's form (`new` and `edit`) pages. - FORM_ATTRIBUTES = [ - :reactable, - :user_id, - :category, - :points, + FORM_ATTRIBUTES = %i[ + reactable + user_id + category + points ].freeze # Overwrite this method to customize how reactions are displayed diff --git a/app/dashboards/tag_dashboard.rb b/app/dashboards/tag_dashboard.rb index 3ee9980011fc0..db383f45a7f66 100644 --- a/app/dashboards/tag_dashboard.rb +++ b/app/dashboards/tag_dashboard.rb @@ -27,7 +27,7 @@ class TagDashboard < Administrate::BaseDashboard text_color_hex: Field::String, alias_for: Field::String, keywords_for_search: Field::String, - taggings_count: Field::Number + taggings_count: Field::Number, }.freeze # COLLECTION_ATTRIBUTES @@ -35,58 +35,58 @@ class TagDashboard < Administrate::BaseDashboard # # By default, it's limited to five items to reduce clutter on index pages. # Feel free to add, remove, or rearrange items. - COLLECTION_ATTRIBUTES = [ - :id, - :name, - :supported, - :alias_for, - :taggings_count + COLLECTION_ATTRIBUTES = %i[ + id + name + supported + alias_for + taggings_count ].freeze # SHOW_PAGE_ATTRIBUTES # an array of attributes that will be displayed on the model's show page. - SHOW_PAGE_ATTRIBUTES = [ - :id, - :name, - :supported, - :tag_moderator_ids, - :alias_for, - :wiki_body_markdown, - :wiki_body_html, - :rules_markdown, - :rules_html, - :short_summary, - :requires_approval, - :submission_template, - :submission_rules_headsup, - :pretty_name, - :profile_image, - :social_image, - :bg_color_hex, - :text_color_hex, - :keywords_for_search + SHOW_PAGE_ATTRIBUTES = %i[ + id + name + supported + tag_moderator_ids + alias_for + wiki_body_markdown + wiki_body_html + rules_markdown + rules_html + short_summary + requires_approval + submission_template + submission_rules_headsup + pretty_name + profile_image + social_image + bg_color_hex + text_color_hex + keywords_for_search ].freeze # FORM_ATTRIBUTES # an array of attributes that will be displayed # on the model's form (`new` and `edit`) pages. - FORM_ATTRIBUTES = [ - :name, - :supported, - :tag_moderator_ids, - :alias_for, - :wiki_body_markdown, - :rules_markdown, - :short_summary, - :requires_approval, - :submission_template, - :submission_rules_headsup, - :pretty_name, - :profile_image, - :social_image, - :bg_color_hex, - :text_color_hex, - :keywords_for_search + FORM_ATTRIBUTES = %i[ + name + supported + tag_moderator_ids + alias_for + wiki_body_markdown + rules_markdown + short_summary + requires_approval + submission_template + submission_rules_headsup + pretty_name + profile_image + social_image + bg_color_hex + text_color_hex + keywords_for_search ].freeze # Overwrite this method to customize how tags are displayed diff --git a/app/dashboards/user_dashboard.rb b/app/dashboards/user_dashboard.rb index 6737db8533128..a6be7b119d86b 100644 --- a/app/dashboards/user_dashboard.rb +++ b/app/dashboards/user_dashboard.rb @@ -53,17 +53,17 @@ class UserDashboard < Administrate::BaseDashboard # # By default, it's limited to four items to reduce clutter on index pages. # Feel free to add, remove, or rearrange items. - COLLECTION_ATTRIBUTES = [ - :profile_image, - :id, - :created_at, - :username, - :name, - :twitter_username, - :github_username, - :following_tags_count, - :saw_onboarding, - :monthly_dues, + COLLECTION_ATTRIBUTES = %i[ + profile_image + id + created_at + username + name + twitter_username + github_username + following_tags_count + saw_onboarding + monthly_dues ].freeze # SHOW_PAGE_ATTRIBUTES @@ -73,28 +73,28 @@ class UserDashboard < Administrate::BaseDashboard # FORM_ATTRIBUTES # an array of attributes that will be displayed # on the model's form (`new` and `edit`) pages. - FORM_ATTRIBUTES = [ - :organization, - :name, - :username, - :twitter_username, - :github_username, - :profile_image, - :org_admin, - :banned, - :reason_for_ban, - :warned, - :reason_for_warning, - :trusted, - :scholar, - :analytics, - :summary, - :website_url, - :bg_color_hex, - :text_color_hex, - :reputation_modifier, - :feed_url, - :saw_onboarding, + FORM_ATTRIBUTES = %i[ + organization + name + username + twitter_username + github_username + profile_image + org_admin + banned + reason_for_ban + warned + reason_for_warning + trusted + scholar + analytics + summary + website_url + bg_color_hex + text_color_hex + reputation_modifier + feed_url + saw_onboarding ].freeze # Overwrite this method to customize how users are displayed diff --git a/app/decorators/article_decorator.rb b/app/decorators/article_decorator.rb index 934dba010f8c5..2a7e2e0b9f99d 100644 --- a/app/decorators/article_decorator.rb +++ b/app/decorators/article_decorator.rb @@ -43,7 +43,7 @@ def title_length_classification end end - def internal_utm_params(place="additional_box") + def internal_utm_params(place = "additional_box") campaign = if boosted_additional_articles "#{organization&.slug}_boosted" else diff --git a/app/decorators/organization_decorator.rb b/app/decorators/organization_decorator.rb index bafd75bf57a39..7aa887b1facc5 100644 --- a/app/decorators/organization_decorator.rb +++ b/app/decorators/organization_decorator.rb @@ -1,6 +1,6 @@ class OrganizationDecorator < ApplicationDecorator delegate_all - + def darker_color(adjustment = 0.88) HexComparer.new([enriched_colors[:bg], enriched_colors[:text]]).brightness(adjustment) end @@ -9,12 +9,12 @@ def enriched_colors if bg_color_hex.blank? { bg: assigned_color[:bg], - text: assigned_color[:text] + text: assigned_color[:text], } else { bg: bg_color_hex || assigned_color[:bg], - text: text_color_hex || assigned_color[:text] + text: text_color_hex || assigned_color[:text], } end end @@ -22,7 +22,7 @@ def enriched_colors def assigned_color { bg: "#0a0a0a", - text: "#ffffff" + text: "#ffffff", } end end diff --git a/app/decorators/user_decorator.rb b/app/decorators/user_decorator.rb index 0b7fc1b4ca5f9..67b8160424bbc 100644 --- a/app/decorators/user_decorator.rb +++ b/app/decorators/user_decorator.rb @@ -15,59 +15,59 @@ def enriched_colors if bg_color_hex.blank? { bg: assigned_color[:bg], - text: assigned_color[:text] + text: assigned_color[:text], } else { bg: bg_color_hex || assigned_color[:bg], - text: text_color_hex || assigned_color[:text] + text: text_color_hex || assigned_color[:text], } end end def assigned_color colors = [ - { - bg: "#093656", - text: "#ffffff" - }, - { - bg: "#19063A", - text: "#dce9f3" - }, - { - bg: "#0D4D4B", - text: "#fdf9f3" - }, - { - bg: "#61122f", - text: "#ffffff" - }, - { - bg: "#edebf6", - text:" #070126" - }, - { - bg: "#080E3B", - text: "#ffffff" - }, - { - bg: "#010C1F", - text: "#aebcd5" - }, - { - bg: "#d7dee2", - text: "#022235" - }, - { - bg: "#161616", - text: "#66e2d5" - }, - { - bg: "#1c0bba", - text: "#c9d2dd" - }, - ] + { + bg: "#093656", + text: "#ffffff", + }, + { + bg: "#19063A", + text: "#dce9f3", + }, + { + bg: "#0D4D4B", + text: "#fdf9f3", + }, + { + bg: "#61122f", + text: "#ffffff", + }, + { + bg: "#edebf6", + text: " #070126", + }, + { + bg: "#080E3B", + text: "#ffffff", + }, + { + bg: "#010C1F", + text: "#aebcd5", + }, + { + bg: "#d7dee2", + text: "#022235", + }, + { + bg: "#161616", + text: "#66e2d5", + }, + { + bg: "#1c0bba", + text: "#c9d2dd", + }, + ] colors[id % 10] end end diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index a8e8bd1cf83e6..b02269cdddccb 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -20,10 +20,10 @@ def core_pages? controller_name == "users" || controller_name == "pages" || controller_name == "chat_channels" || - controller_name == "dashboards"|| - controller_name == "moderations"|| - controller_name == "videos"|| - controller_name == "badges"|| + controller_name == "dashboards" || + controller_name == "moderations" || + controller_name == "videos" || + controller_name == "badges" || controller_name == "stories" || controller_name == "comments" || controller_name == "notifications" || @@ -36,16 +36,16 @@ def render_js? def title(page_title) derived_title = if page_title.include?("DEV") - page_title - else - page_title + " - DEV Community 👩‍💻👨‍💻" + page_title + else + page_title + " - DEV Community 👩‍💻👨‍💻" end - content_for(:title){ derived_title } + content_for(:title) { derived_title } derived_title end def icon(name, pixels = "20") - image_tag icon_url(name), alt: name, class:"icon-img", height: pixels, width: pixels + image_tag icon_url(name), alt: name, class: "icon-img", height: pixels, width: pixels end def icon_url(name) @@ -66,11 +66,11 @@ def icon_url(name) end end - def cloudinary(url, width = nil, quality = 80, format = "jpg") + def cloudinary(url, width = nil, _quality = 80, _format = "jpg") if Rails.env.development? && (url.blank? || !url.include?("http")) return url end - if url && url.size.positive? + if url&.size&.positive? if width "https://res.cloudinary.com/practicaldev/image/fetch/c_scale,fl_progressive,q_auto,w_#{width}/f_auto/#{url}" else @@ -121,7 +121,7 @@ def cloud_social_image(article) def tag_colors(tag) Rails.cache.fetch("view-helper-#{tag}/tag_colors", expires_in: 5.hours) do if found_tag = Tag.find_by_name(tag) - { background: found_tag.bg_color_hex,color: found_tag.text_color_hex } + { background: found_tag.bg_color_hex, color: found_tag.text_color_hex } else { background: "#d6d9e0", color: "#606570" } end @@ -130,7 +130,7 @@ def tag_colors(tag) def beautified_url(url) url.sub(/^((http[s]?|ftp):\/)?\//, "").sub(/\?.*/, "").chomp("/") - rescue + rescue StandardError url end diff --git a/app/helpers/articles_helper.rb b/app/helpers/articles_helper.rb index ccf5d13e9c155..a891cfee93698 100644 --- a/app/helpers/articles_helper.rb +++ b/app/helpers/articles_helper.rb @@ -1,11 +1,10 @@ module ArticlesHelper - def hasVid(article) article.processed_html.include?("youtube.com/embed/") || article.processed_html.include?("player.vimeo.com") || article.comments_blob.include?("youtube") end - def collection_link_class(current_article,linked_article) - if (current_article.id == linked_article.id) + def collection_link_class(current_article, linked_article) + if current_article.id == linked_article.id "current-article" elsif !linked_article.published "coming-soon" @@ -14,15 +13,15 @@ def collection_link_class(current_article,linked_article) def image_tag_or_inline_svg(service_name) if is_internal_navigation? - image_tag("#{service_name}-logo.svg", class:"icon-img") + image_tag("#{service_name}-logo.svg", class: "icon-img") else - inline_svg("#{service_name}-logo.svg", class:"icon-img") + inline_svg("#{service_name}-logo.svg", class: "icon-img") end end def should_show_updated_on?(article) article.edited_at && - article.published && + article.published && !article.published_from_feed && article.published_at.next_day < article.edited_at end @@ -42,7 +41,7 @@ def get_host_without_www(url) host.start_with?("www.") ? host[4..-1] : host end - def is_hiring_form?(tag,article) + def is_hiring_form?(tag, article) tag.to_s == "hiring" || article.tag_list.include?("hiring") end end diff --git a/app/labor/badge_rewarder.rb b/app/labor/badge_rewarder.rb index c9863a19ec525..17f7928b8a55c 100644 --- a/app/labor/badge_rewarder.rb +++ b/app/labor/badge_rewarder.rb @@ -5,7 +5,8 @@ def self.award_yearly_club_badges achievement = BadgeAchievement.create( user_id: user.id, badge_id: 2, - rewarding_context_message_markdown: message) + rewarding_context_message_markdown: message, + ) user.save if achievement.valid? # ID 2 is the proper ID in prod. We should change in future to ENV var. end @@ -17,7 +18,8 @@ def self.award_beloved_comment_badges achievement = BadgeAchievement.create( user_id: comment.user_id, badge_id: 3, - rewarding_context_message_markdown: message) + rewarding_context_message_markdown: message, + ) comment.user.save if achievement.valid? # ID 3 is the proper ID in prod. We should change in future to ENV var. end @@ -28,7 +30,8 @@ def self.reward_top_seven_badges(usernames) BadgeAchievement.create( user_id: user.id, badge_id: Badge.find_by_slug("top-7").id, - rewarding_context_message_markdown: "Congrats!!!") + rewarding_context_message_markdown: "Congrats!!!", + ) user.save end end diff --git a/app/labor/cache_buster.rb b/app/labor/cache_buster.rb index 1967bbdf3fdc8..b5233b4e85691 100644 --- a/app/labor/cache_buster.rb +++ b/app/labor/cache_buster.rb @@ -1,12 +1,11 @@ class CacheBuster - def bust(path) return unless Rails.env.production? request = HTTParty.post("https://api.fastly.com/purge/https://dev.to#{path}", - :headers => { 'Fastly-Key' => 'f15066a3abedf47238b08e437684c84f' } ) + headers: { "Fastly-Key" => "f15066a3abedf47238b08e437684c84f" }) request = HTTParty.post("https://api.fastly.com/purge/https://dev.to#{path}?i=i", - :headers => { 'Fastly-Key' => 'f15066a3abedf47238b08e437684c84f' } ) - return request + headers: { "Fastly-Key" => "f15066a3abedf47238b08e437684c84f" }) + request end def bust_comment(comment) @@ -22,10 +21,10 @@ def bust_comment(comment) bust("?i=i") end bust("#{comment.commentable.path}/comments/") - bust("#{comment.commentable.path}") + bust(comment.commentable.path.to_s) comment.commentable.comments.each do |c| bust(c.path) - bust(c.path+"?i=i") + bust(c.path + "?i=i") end bust("#{comment.commentable.path}/comments/*") bust("/#{comment.user.username}") @@ -50,10 +49,8 @@ def bust_article(article) bust("/api/articles/#{article.id}") bust("/api/articles/by_path?url=#{article.path}") - if article.collection - article.collection.articles.each do |a| - bust(a.path) - end + article.collection&.articles&.each do |a| + bust(a.path) end end @@ -62,7 +59,7 @@ def bust_home_pages(article) bust("/") bust("?i=i") end - [[1.week.ago, "week"],[1.month.ago, "month"],[1.year.ago, "year"],[5.years.ago, "infinity"]].each do |timeframe| + [[1.week.ago, "week"], [1.month.ago, "month"], [1.year.ago, "year"], [5.years.ago, "infinity"]].each do |timeframe| if Article.where(published: true).where("published_at > ?", timeframe[0]). order("positive_reactions_count DESC").limit(4).pluck(:id).include?(article.id) bust("/top/#{timeframe[1]}") @@ -88,7 +85,7 @@ def bust_tag_pages(article) bust("/t/#{tag}/latest") bust("/t/#{tag}/latest?i=i") end - [[1.week.ago, "week"],[1.month.ago, "month"],[1.year.ago, "year"],[5.years.ago, "infinity"]]. + [[1.week.ago, "week"], [1.month.ago, "month"], [1.year.ago, "year"], [5.years.ago, "infinity"]]. each do |timeframe| if Article.where(published: true).where("published_at > ?", timeframe[0]).tagged_with(tag). order("positive_reactions_count DESC").limit(3).pluck(:id).include?(article.id) diff --git a/app/labor/color_from_image.rb b/app/labor/color_from_image.rb index c392811777b8f..1d563f53a256f 100644 --- a/app/labor/color_from_image.rb +++ b/app/labor/color_from_image.rb @@ -1,5 +1,4 @@ class ColorFromImage - def initialize(url) @url = url end @@ -8,19 +7,17 @@ def main return "#000000" unless Rails.env.production? begin get_palette["colors"][0]["hex"] - rescue + rescue StandardError "#dddddd" end end def get_palette input = { - url: @url + url: @url, } client = Algorithmia.client(ApplicationConfig["ALGORITHMIA_KEY"]) - algo = client.algo('vagrant/ColorSchemeExtraction/0.2.0') + algo = client.algo("vagrant/ColorSchemeExtraction/0.2.0") algo.pipe(input).result end - - end diff --git a/app/labor/error_message_cleaner.rb b/app/labor/error_message_cleaner.rb index b84293870ba77..99163c3dd2d11 100644 --- a/app/labor/error_message_cleaner.rb +++ b/app/labor/error_message_cleaner.rb @@ -1,5 +1,4 @@ class ErrorMessageCleaner - attr_accessor :error_message def initialize(error_message) @@ -13,5 +12,4 @@ def clean error_message end end - end diff --git a/app/labor/follow_checker.rb b/app/labor/follow_checker.rb index 5832752086e24..4970ba32c4198 100644 --- a/app/labor/follow_checker.rb +++ b/app/labor/follow_checker.rb @@ -1,5 +1,4 @@ class FollowChecker - attr_accessor :follower, :followable_type, :followable_id def initialize(follower, followable_type, followable_id) diff --git a/app/labor/hex_comparer.rb b/app/labor/hex_comparer.rb index 0ebc982e3049b..e5897a537bc15 100644 --- a/app/labor/hex_comparer.rb +++ b/app/labor/hex_comparer.rb @@ -1,5 +1,4 @@ class HexComparer - attr_accessor :hexes, :amount def initialize(hexes, amount = 1) @hexes = hexes @@ -19,32 +18,29 @@ def biggest end def brightness(amount = 1) - begin - rgb = smallest.gsub("#","").scan(/../).map(&:hex).map{ |color| color * amount }.map(&:round) - "#%02x%02x%02x" % rgb - rescue - smallest - end + rgb = smallest.gsub("#", "").scan(/../).map(&:hex).map { |color| color * amount }.map(&:round) + "#%02x%02x%02x" % rgb + rescue StandardError + smallest end - def accent() - if brightness(1.14 ** amount).size == 7 - brightness(1.14 ** amount) - elsif brightness(1.08 ** amount).size == 7 - brightness(1.08 ** amount) - elsif brightness(1.06 ** amount).size == 7 - brightness(1.06 ** amount) - elsif brightness(0.96 ** amount).size == 7 - brightness(0.96 ** amount) - elsif brightness(0.9 ** amount).size == 7 - brightness(0.9 ** amount) - elsif brightness(0.8 ** amount).size == 7 - brightness(0.8 ** amount) - elsif brightness(0.7 ** amount).size == 7 - brightness(0.7 ** amount) - elsif brightness(0.6 ** amount).size == 7 - brightness(0.6 ** amount) + def accent + if brightness(1.14**amount).size == 7 + brightness(1.14**amount) + elsif brightness(1.08**amount).size == 7 + brightness(1.08**amount) + elsif brightness(1.06**amount).size == 7 + brightness(1.06**amount) + elsif brightness(0.96**amount).size == 7 + brightness(0.96**amount) + elsif brightness(0.9**amount).size == 7 + brightness(0.9**amount) + elsif brightness(0.8**amount).size == 7 + brightness(0.8**amount) + elsif brightness(0.7**amount).size == 7 + brightness(0.7**amount) + elsif brightness(0.6**amount).size == 7 + brightness(0.6**amount) end end - end diff --git a/app/labor/html_cleaner.rb b/app/labor/html_cleaner.rb index c4bb1fd4ebe71..6fca5b5e5ecf7 100644 --- a/app/labor/html_cleaner.rb +++ b/app/labor/html_cleaner.rb @@ -1,10 +1,9 @@ class HtmlCleaner - def clean_html(html) doc = Nokogiri::HTML(html) # Remove Medium tracking pixel doc.css("img").each do |img| - if img.attr('src') && (img.attr('src').include? "medium.com/_/stat") + if img.attr("src") && (img.attr("src").include? "medium.com/_/stat") img.remove end end @@ -15,13 +14,11 @@ def clean_html(html) end end - doc.css('figure').each do |el| - el.name = 'p' + doc.css("figure").each do |el| + el.name = "p" end - doc.xpath('//@class').remove + doc.xpath("//@class").remove doc.to_html end - - end diff --git a/app/labor/language_detector.rb b/app/labor/language_detector.rb index 4ce8e3b4e0f7e..6139d0c644a17 100644 --- a/app/labor/language_detector.rb +++ b/app/labor/language_detector.rb @@ -1,22 +1,19 @@ class LanguageDetector - def initialize(article) @article = article end def detect - begin - response = get_language - response["result"] if response["confidence"] > 0.8 - rescue - nil - end + response = get_language + response["result"] if response["confidence"] > 0.8 + rescue StandardError + nil end def get_language return { "result" => "en", "confidence" => 0.9 } unless Rails.env.production? client = Algorithmia.client(ApplicationConfig["ALGORITHMIA_KEY"]) - algo = client.algo('miguelher/LanguageDetector/0.1.0') + algo = client.algo("miguelher/LanguageDetector/0.1.0") algo.pipe(text).result end diff --git a/app/labor/markdown_parser.rb b/app/labor/markdown_parser.rb index 856d38b3aa07b..780a0577d6003 100644 --- a/app/labor/markdown_parser.rb +++ b/app/labor/markdown_parser.rb @@ -14,7 +14,7 @@ def evaluate_markdown renderer = Redcarpet::Render::HTMLRouge.new(hard_wrap: true, filter_html: false) markdown = Redcarpet::Markdown.new(renderer, REDCARPET_CONFIG) tag_whitelist = %w(strong em p h1 h2 h3 h4 h5 h6 i u b code pre - br ul ol li small sup sub img a span hr blockquote) + br ul ol li small sup sub img a span hr blockquote) attribute_whitelist = %w(href strong em ref rel src title alt class) ActionController::Base.helpers.sanitize markdown.render(@content).html_safe, tags: tag_whitelist, diff --git a/app/labor/notification_counter.rb b/app/labor/notification_counter.rb index 452fcf2db48d6..225d85c242c7a 100644 --- a/app/labor/notification_counter.rb +++ b/app/labor/notification_counter.rb @@ -1,15 +1,14 @@ class NotificationCounter - def initialize(user) @user = user end def unread_notification_count return 0 if Rails.env.test? - StreamRails.feed_manager.get_notification_feed(@user.id).get['unseen'] + StreamRails.feed_manager.get_notification_feed(@user.id).get["unseen"] end def set_to_zero - StreamRails.feed_manager.get_notification_feed(@user.id).get(mark_seen:true) + StreamRails.feed_manager.get_notification_feed(@user.id).get(mark_seen: true) end end diff --git a/app/labor/podcast_feed.rb b/app/labor/podcast_feed.rb index bdc491ed566ef..8385d78c84a8a 100644 --- a/app/labor/podcast_feed.rb +++ b/app/labor/podcast_feed.rb @@ -19,8 +19,8 @@ def get_episodes(podcast, num = 1000) update_existing_episode(ep, item, podcast) end end - return feed.items.size - rescue => e + feed.items.size + rescue StandardError => e puts e.message end @@ -36,19 +36,19 @@ def create_new_episode(item, podcast) get_media_url(ep, item, podcast) begin ep.published_at = item.pubDate.to_date - rescue + rescue StandardError puts "not valid date" end ep.body = item.content_encoded || item.itunes_summary || item.description ep.save! end - def update_existing_episode(ep, item, podcast) + def update_existing_episode(ep, item, _podcast) if ep.published_at == nil begin ep.published_at = item.pubDate.to_date ep.save - rescue + rescue StandardError puts "not valid date" end end @@ -65,12 +65,12 @@ def existing_episode(item, podcast) def get_media_url(ep, item, podcast) ep.media_url = if Rails.env.test? || - open(item.enclosure.url.gsub(/http:/, "https:")).status[0] == "200" + open(item.enclosure.url.gsub(/http:/, "https:")).status[0] == "200" item.enclosure.url.gsub(/http:/, "https:") else item.enclosure.url end - rescue + rescue StandardError # podcast episode must have a media_url ep.media_url = item.enclosure.url if podcast.status_notice.empty? @@ -80,12 +80,12 @@ def get_media_url(ep, item, podcast) def update_media_url(ep, item) if ep.media_url.include?("https") - return + nil elsif !ep.media_url.include?("https") && item.enclosure.url.include?("https") ep.update!(media_url: item.enclosure.url) end - rescue + rescue StandardError logger.info "something went wrong with #{podcast.title}, #{ep.title} -- #{ep.media_url}" end end diff --git a/app/labor/rate_limit_checker.rb b/app/labor/rate_limit_checker.rb index 479b31f07dbfd..2446c9f7fdd96 100644 --- a/app/labor/rate_limit_checker.rb +++ b/app/labor/rate_limit_checker.rb @@ -6,16 +6,16 @@ def initialize(user = nil) def limit_by_situation(situation) result = false - case situation - when "comment_creation" - result = user.comments.where("created_at > ?", 30.seconds.ago).size > 9 - when "published_article_creation" - result = user.articles. - where(published: true). - where("created_at > ?", 30.seconds.ago).size > 9 - else - result = false - end + result = case situation + when "comment_creation" + user.comments.where("created_at > ?", 30.seconds.ago).size > 9 + when "published_article_creation" + user.articles. + where(published: true). + where("created_at > ?", 30.seconds.ago).size > 9 + else + false + end ping_admins if result == true result end @@ -29,7 +29,7 @@ def limit_by_email_recipient_address(address) def ping_admins return unless user SlackBot.ping( - "Rate limit exceeded. https://dev.to#{user.path}", + "Rate limit exceeded. https://dev.to#{user.path}", channel: "abuse-reports", username: "rate_limit", icon_emoji: ":hand:", diff --git a/app/labor/reaction_image.rb b/app/labor/reaction_image.rb index dfd627fe7574b..9bc1bff731deb 100644 --- a/app/labor/reaction_image.rb +++ b/app/labor/reaction_image.rb @@ -7,11 +7,11 @@ def initialize(category) def path images = { - 'like' => 'emoji/emoji-one-heart.png', - 'unicorn' => 'emoji/emoji-one-unicorn.png', - 'hands' => 'emoji/emoji-one-hands.png', - 'thinking' => 'emoji/emoji-one-thinking.png', - 'readinglist' => 'emoji/emoji-one-bookmark.png' + "like" => "emoji/emoji-one-heart.png", + "unicorn" => "emoji/emoji-one-unicorn.png", + "hands" => "emoji/emoji-one-hands.png", + "thinking" => "emoji/emoji-one-thinking.png", + "readinglist" => "emoji/emoji-one-bookmark.png", }.freeze images[category] end diff --git a/app/labor/reading_list.rb b/app/labor/reading_list.rb index d551c53d21235..1644bd609816e 100644 --- a/app/labor/reading_list.rb +++ b/app/labor/reading_list.rb @@ -29,4 +29,4 @@ def count def reaction_criteria { user_id: user.id, reactable_type: "Article", category: "readinglist" } end -end \ No newline at end of file +end diff --git a/app/labor/timeframer.rb b/app/labor/timeframer.rb index 7e8905c01b6c5..39d84e08f9761 100644 --- a/app/labor/timeframer.rb +++ b/app/labor/timeframer.rb @@ -1,5 +1,4 @@ class Timeframer - attr_accessor :timeframe def initialize(timeframe) @timeframe = timeframe @@ -18,5 +17,4 @@ def datetime "latest" end end - -end \ No newline at end of file +end diff --git a/app/labor/twilio_token.rb b/app/labor/twilio_token.rb index 172124660d202..4858a123a69db 100644 --- a/app/labor/twilio_token.rb +++ b/app/labor/twilio_token.rb @@ -16,7 +16,7 @@ def get api_key, api_secret, [], - identity: user.id + identity: user.id, ) grant = Twilio::JWT::AccessToken::VideoGrant.new @@ -25,5 +25,4 @@ def get token.to_jwt end - end diff --git a/app/labor/unread_notifications_emailer.rb b/app/labor/unread_notifications_emailer.rb index 3727930bb09e0..f55b719449282 100644 --- a/app/labor/unread_notifications_emailer.rb +++ b/app/labor/unread_notifications_emailer.rb @@ -7,13 +7,11 @@ def self.send_all_emails(num = 1000) # We can change this up later. users = User.where("comments_count > ? OR reactions_count > ?", 0, 0).order("RANDOM()").limit(num) users.find_each do |user| - begin - UnreadNotificationsEmailer.new(user).send_email_if_appropriate - rescue => e - logger = Logger.new(STDOUT) - logger = Airbrake::AirbrakeLogger.new(logger) - logger.error(e) - end + UnreadNotificationsEmailer.new(user).send_email_if_appropriate + rescue StandardError => e + logger = Logger.new(STDOUT) + logger = Airbrake::AirbrakeLogger.new(logger) + logger.error(e) end end @@ -56,7 +54,7 @@ def proper_activity(activity) def last_email_sent_after(time) last_email = user.email_messages.last - time_check = last_email && last_email.sent_at && (last_email.sent_at > time) + time_check = last_email&.sent_at && (last_email.sent_at > time) time_check.present? end end diff --git a/app/labor/user_states.rb b/app/labor/user_states.rb index 60abfa1292181..0f7483669e831 100644 --- a/app/labor/user_states.rb +++ b/app/labor/user_states.rb @@ -19,26 +19,26 @@ def cached_onboarding_checklist end def made_first_article - user.articles.where(published:true).size > 0 + !user.articles.where(published: true).empty? end def follows_a_tag - user.follows.where(followable_type:"ActsAsTaggableOn::Tag").size > 0 + !user.follows.where(followable_type: "ActsAsTaggableOn::Tag").empty? end def fill_out_your_profile - user.summary.present? && user.summary.size > 0 + user.summary.present? && !user.summary.empty? end def leave_reactions - user.reactions.size > 0 + !user.reactions.empty? end def follow_people - user.follows.where(followable_type:"User").size > 0 + !user.follows.where(followable_type: "User").empty? end def leave_comments - user.comments.size > 0 + !user.comments.empty? end end diff --git a/app/liquid_tags/codepen_tag.rb b/app/liquid_tags/codepen_tag.rb index f772a134b3726..4cca541e1db3b 100644 --- a/app/liquid_tags/codepen_tag.rb +++ b/app/liquid_tags/codepen_tag.rb @@ -5,7 +5,7 @@ def initialize(tag_name, link, tokens) @height = 600 end - def render(context) + def render(_context) html = <<-HTML - - + + + HTML finalize_html(html) end @@ -33,7 +33,7 @@ def parse_id(input) end def valid_id?(id) - id.length == 11 && !(id !~ /[a-zA-Z0-9_-]{11}/) + id.length == 11 && id =~ /[a-zA-Z0-9_-]{11}/ end end diff --git a/app/liquid_tags/link_tag.rb b/app/liquid_tags/link_tag.rb index 445e5999aba2f..10c244b6e6300 100644 --- a/app/liquid_tags/link_tag.rb +++ b/app/liquid_tags/link_tag.rb @@ -2,11 +2,11 @@ class LinkTag < LiquidTagBase include ActionView::Helpers attr_reader :article - def initialize(tag_name, url, tokens) + def initialize(_tag_name, url, _tokens) @article = parse_url_for_article(url) end - def render(context) + def render(_context) tags = article.tag_list.map { |t| "##{t}" }.join <<-HTML "\ + "" end def self.script @@ -82,11 +82,11 @@ def self.script private def parse_id(input) - input_no_space = input.delete(' ') + input_no_space = input.delete(" ") if valid_id?(input_no_space) input_no_space else - raise StandardError, 'Invalid Twitter Id' + raise StandardError, "Invalid Twitter Id" end end diff --git a/app/liquid_tags/user_tag.rb b/app/liquid_tags/user_tag.rb index bab8328e5ff5d..077a7fc475931 100644 --- a/app/liquid_tags/user_tag.rb +++ b/app/liquid_tags/user_tag.rb @@ -2,11 +2,11 @@ class UserTag < LiquidTagBase include ApplicationHelper attr_reader :user - def initialize(tag_name, user, tokens) + def initialize(_tag_name, user, _tokens) @user = parse_username_to_user(user) end - def render(context) + def render(_context) # looks like link liquid tag <<-HTML
@@ -14,7 +14,7 @@ def render(context) .ltag__user__id__#{@user.id} .follow-action-button{ background-color: #{user_colors(@user)[:bg]} !important; color: #{user_colors(@user)[:text]} !important; - border-color: #{ user_colors(@user)[:bg].downcase == '#ffffff' ? user_colors(@user)[:text] : user_colors(@user)[:bg] } !important; + border-color: #{user_colors(@user)[:bg].casecmp('#ffffff').zero? ? user_colors(@user)[:text] : user_colors(@user)[:bg]} !important; } @@ -54,7 +54,7 @@ def twitter_link if @user.twitter_username.present? <<-HTML - #{image_tag('/assets/twitter-logo.svg', class:'icon-img', alt: 'twitter')} #{@user.twitter_username} + #{image_tag('/assets/twitter-logo.svg', class: 'icon-img', alt: 'twitter')} #{@user.twitter_username} HTML end @@ -64,7 +64,7 @@ def github_link if @user.github_username.present? <<-HTML - #{image_tag('/assets/github-logo.svg', class:'icon-img', alt: 'github')} #{@user.github_username} + #{image_tag('/assets/github-logo.svg', class: 'icon-img', alt: 'github')} #{@user.github_username} HTML end @@ -74,7 +74,7 @@ def website_link if @user.website_url.present? <<-HTML - #{image_tag('/assets/link.svg', class:'icon-img', alt: 'website link')} #{beautified_url(@user.website_url)} + #{image_tag('/assets/link.svg', class: 'icon-img', alt: 'website link')} #{beautified_url(@user.website_url)} HTML end diff --git a/app/liquid_tags/youtube_tag.rb b/app/liquid_tags/youtube_tag.rb index 22b684efec134..50f22288e1c47 100644 --- a/app/liquid_tags/youtube_tag.rb +++ b/app/liquid_tags/youtube_tag.rb @@ -6,7 +6,7 @@ def initialize(tag_name, id, tokens) @height = 399 end - def render(context) + def render(_context) html = <<-HTML
" + html = "
" # rubocop:disable Metrics/LineLength expect(generate_instagram_tag(valid_id).render).to eq(html.chomp("\n")) end diff --git a/spec/liquid_tags/podcast_tag_spec.rb b/spec/liquid_tags/podcast_tag_spec.rb index b6b77f99ae255..de3ec8e876374 100644 --- a/spec/liquid_tags/podcast_tag_spec.rb +++ b/spec/liquid_tags/podcast_tag_spec.rb @@ -1,32 +1,32 @@ -require 'rails_helper' +require "rails_helper" RSpec.describe PodcastTag, type: :liquid_template do let(:podcast) { create(:podcast) } let(:podcast_episode) { create(:podcast_episode, podcast_id: podcast.id) } let(:valid_long_slug) { "/#{podcast.slug}/#{podcast_episode.slug}" } - before { Liquid::Template.register_tag('podcast', PodcastTag) } + before { Liquid::Template.register_tag("podcast", PodcastTag) } def generate_podcast_liquid_tag(link) Liquid::Template.parse("{% podcast #{link} %}") end - context 'when given valid link' do - it 'fetches target podcast' do + context "when given valid link" do + it "fetches target podcast" do liquid = generate_podcast_liquid_tag(valid_long_slug) expect(liquid.root.nodelist.first.episode).to eq(podcast_episode) end - it 'raises error if podcast does not exist' do + it "raises error if podcast does not exist" do expect do - generate_podcast_liquid_tag(valid_long_slug + '1') + generate_podcast_liquid_tag(valid_long_slug + "1") end.to raise_error(StandardError) end end - it 'rejects invalid link' do + it "rejects invalid link" do expect do - generate_podcast_liquid_tag('https://dev.to/toolsday/hardware/test/2') + generate_podcast_liquid_tag("https://dev.to/toolsday/hardware/test/2") end.to raise_error(StandardError) end end diff --git a/spec/liquid_tags/replit_tag_spec.rb b/spec/liquid_tags/replit_tag_spec.rb index e2fb1b61f15ad..0ea3ff60bf637 100644 --- a/spec/liquid_tags/replit_tag_spec.rb +++ b/spec/liquid_tags/replit_tag_spec.rb @@ -1,19 +1,20 @@ -require 'rails_helper' +require "rails_helper" RSpec.describe ReplitTag, type: :liquid_template do - describe '#id' do - let(:replit_id) { 'dQw4w9WgXcQ' } + describe "#id" do + let(:replit_id) { "dQw4w9WgXcQ" } + def generate_new_liquid(id) - Liquid::Template.register_tag('replit', ReplitTag) + Liquid::Template.register_tag("replit", ReplitTag) Liquid::Template.parse("{% replit #{id} %}") end - it 'accepts replit id' do + it "accepts replit id" do liquid = generate_new_liquid(replit_id) expect(liquid.render).to include('
') end - it 'renders iframe' do + it "renders iframe" do liquid = generate_new_liquid(replit_id) expect(liquid.render).to include(" '\ - '' + "allowfullscreen> "\ + "" end - it 'accepts youtube video id' do + it "accepts youtube video id" do liquid = generate_new_liquid(youtube_id) expect(liquid.render).to eq(generate_iframe(youtube_id)) end - it 'accepts youtube video id with empty space' do - liquid = generate_new_liquid(youtube_id + ' ') + it "accepts youtube video id with empty space" do + liquid = generate_new_liquid(youtube_id + " ") expect(liquid.render).to eq(generate_iframe(youtube_id)) end - it 'rejects invalid youtube video id' do - expect { - generate_new_liquid('really_long_invalid_id') - }.to raise_error(StandardError) + it "rejects invalid youtube video id" do + expect do + generate_new_liquid("really_long_invalid_id") + end.to raise_error(StandardError) end end end diff --git a/spec/mailers/membership_mailer_spec.rb b/spec/mailers/membership_mailer_spec.rb index cb8bceb408397..2e812e5316979 100644 --- a/spec/mailers/membership_mailer_spec.rb +++ b/spec/mailers/membership_mailer_spec.rb @@ -6,12 +6,17 @@ describe "#new_membership_subscription_email" do it "renders proper subject" do user = create(:user) - new_membership_subscription_email = described_class.new_membership_subscription_email(user, "level_1_member") + new_membership_subscription_email = described_class.new_membership_subscription_email( + user, "level_1_member" + ) expect(new_membership_subscription_email.subject).to include("Thanks for subscribing") end + it "renders proper receiver" do user = create(:user) - new_membership_subscription_email = described_class.new_membership_subscription_email(user, "level_1_member") + new_membership_subscription_email = described_class.new_membership_subscription_email( + user, "level_1_member" + ) expect(new_membership_subscription_email.to).to eq([user.email]) end end diff --git a/spec/mailers/notify_mailer_spec.rb b/spec/mailers/notify_mailer_spec.rb index f03a6218a53f1..4a60a211cee28 100644 --- a/spec/mailers/notify_mailer_spec.rb +++ b/spec/mailers/notify_mailer_spec.rb @@ -50,20 +50,23 @@ describe "#new_badge_email" do let(:badge) { create(:badge) } + def create_badge_achievement(user, badge, rewarder) + BadgeAchievement.create( + user_id: user.id, + badge_id: badge.id, + rewarder_id: rewarder.id, + rewarding_context_message_markdown: "Hello [Yoho](/hey)", + ) + end + it "renders proper subject" do - badge_achievement = BadgeAchievement.create(user_id: user.id, - badge_id: badge.id, - rewarder_id: user2.id, - rewarding_context_message_markdown: "Hello [Yoho](/hey)") + badge_achievement = create_badge_achievement(user, badge, user2) new_badge_email = described_class.new_badge_email(badge_achievement) expect(new_badge_email.subject).to eq("You just got a badge") end it "renders proper receiver" do - badge_achievement = BadgeAchievement.create(user_id: user.id, - badge_id: badge.id, - rewarder_id: user2.id, - rewarding_context_message_markdown: "Hello [Yoho](/hey)") + badge_achievement = create_badge_achievement(user, badge, user2) new_badge_email = described_class.new_badge_email(badge_achievement) expect(new_badge_email.to).to eq([user.email]) end diff --git a/spec/models/article_spec.rb b/spec/models/article_spec.rb index 676647c4c8ad1..e86bf54d165e2 100644 --- a/spec/models/article_spec.rb +++ b/spec/models/article_spec.rb @@ -1,3 +1,4 @@ +# rubocop:disable RSpec/ExampleLength, RSpec/MultipleExpectations require "rails_helper" RSpec.describe Article, type: :model do @@ -24,10 +25,13 @@ def build_and_validate_article(*args) it { is_expected.to have_many(:reactions) } it { is_expected.to have_many(:notifications) } it { is_expected.to validate_presence_of(:user_id) } - it { is_expected.to_not allow_value("foo").for(:main_image_background_hex_color)} + it { is_expected.not_to allow_value("foo").for(:main_image_background_hex_color) } + + context "when published" do + before do + allow(subject).to receive(:published?).and_return(true) # rubocop:disable RSpec/NamedSubject + end - context "if published" do - before { allow(subject).to receive(:published?).and_return(true) } it { is_expected.to validate_presence_of(:slug) } end @@ -89,12 +93,13 @@ def build_and_validate_article(*args) describe "featured_number" do it "is updated if approved when already true" do - article.body_markdown = "---\ntitle: Hellohnnnn#{rand(1000)}\npublished: true\ntags: hiring\n---\n\nHello" + body = "---\ntitle: Hellohnnnn#{rand(1000)}\npublished: true\ntags: hiring\n---\n\nHello" + article.body_markdown = body article.save article.approved = true article.save sleep(1) - article.body_markdown = "---\ntitle: Hellohnnnn#{rand(1000)}\npublished: true\ntags: hiring\n---\n\nHellos" + article.body_markdown = body + "s" article.approved = true article.save! expect(article.featured_number).not_to eq(article.updated_at.to_i) @@ -211,51 +216,43 @@ def build_and_validate_article(*args) end describe "queries" do - it "returns article plucked objects that match keyword query" do + let(:search_keyword) do create(:search_keyword, google_result_path: article.path, google_position: 8, google_volume: 2000, google_difficulty: 10) + end + + it "returns article plucked objects that match keyword query" do + search_keyword article.update(featured: true) articles = Article.seo_boostable expect(articles.flatten[0]).to eq(article.path) end + it "returns keyword articles by tag" do - create(:search_keyword, - google_result_path: article.path, - google_position: 8, - google_volume: 2000, - google_difficulty: 10) + search_keyword article.update(featured: true) articles = Article.seo_boostable(article.tags.first) expect(articles.flatten[0]).to eq(article.path) end + it "does not return articles when none match based on tag" do - create(:search_keyword, - google_result_path: article.path, - google_position: 8, - google_volume: 2000, - google_difficulty: 10) + search_keyword article.update(featured: true) articles = Article.seo_boostable("woozle-wozzle-20000") expect(articles.size).to eq(0) end - it "does not return keywords that don't match criteria plucked objects that match keyword query" do - create(:search_keyword, - google_result_path: article.path, - google_position: 33, #too high position - google_volume: 2000, - google_difficulty: 10) + + it "doesn't return keywords that don't match criteria plucked objects matching keyword query" do + search_keyword.update_attributes(google_position: 33) # too high of a position articles = Article.seo_boostable expect(articles.size).to eq(0) end + it "does not return unpublished articles" do - create(:search_keyword, - google_result_path: article.path, - google_position: 8, - google_volume: 2000, - google_difficulty: 10) + search_keyword articles = Article.seo_boostable article.update(published: false) expect(articles.size).to eq(0) @@ -370,15 +367,15 @@ def build_and_validate_article(*args) end it "returns a hash with the flare tag's name" do - expect(FlareTag.new(valid_article).tag_hash.values.include?("ama")).to be true + expect(FlareTag.new(valid_article).tag_hash.value?("ama")).to be true end it "returns a hash with the flare tag's bg_color_hex" do - expect(FlareTag.new(valid_article).tag_hash.values.include?("#f3f3f3")).to be true + expect(FlareTag.new(valid_article).tag_hash.value?("#f3f3f3")).to be true end it "returns a hash with the flare tag's text_color_hex" do - expect(FlareTag.new(valid_article).tag_hash.values.include?("#cccccc")).to be true + expect(FlareTag.new(valid_article).tag_hash.value?("#cccccc")).to be true end end @@ -442,5 +439,5 @@ def build_and_validate_article(*args) last_year = 1.year.ago.year % 100 expect(article.readable_publish_date.include?("'#{last_year}")).to eq(true) end - end +# rubocop:enable RSpec/ExampleLength, RSpec/MultipleExpectations diff --git a/spec/models/block_spec.rb b/spec/models/block_spec.rb index 6a9fe26936337..180288cf8a227 100644 --- a/spec/models/block_spec.rb +++ b/spec/models/block_spec.rb @@ -1,28 +1,21 @@ require "rails_helper" RSpec.describe Block, type: :model do + let(:user) { create(:user) } + let(:block) { Block.new(user: user, input_html: "hello") } - it "creates processed_html after publishd!" do - user = create(:user) + it "creates processed_html after published!" do user.add_role(:super_admin) - block = Block.new - block.input_html = "hello" - block.user_id = user.id block.publish! expect(block.processed_html).to eq("hello") end it "is not valid without user" do - block = Block.new - block.input_html = "hello" + block.user = nil expect(block).not_to be_valid end - it "is not valid non-admin user" do - user = create(:user) - block = Block.new - block.user_id = user.id - block.input_html = "hello" + it "is not valid with non-admin user" do expect(block).not_to be_valid end end diff --git a/spec/models/chat_channel_spec.rb b/spec/models/chat_channel_spec.rb index c96e72bcbf8a3..5044eb885aece 100644 --- a/spec/models/chat_channel_spec.rb +++ b/spec/models/chat_channel_spec.rb @@ -1,3 +1,4 @@ +# rubocop:disable RSpec/MultipleExpectations require "rails_helper" RSpec.describe ChatChannel, type: :model do @@ -23,8 +24,13 @@ chat_channel = ChatChannel.create_with_users([create(:user), create(:user)]) expect(chat_channel.active_users.size).to eq(2) expect(chat_channel.channel_users.size).to eq(2) + end + + it "decreases active users if one leaves" do + chat_channel = ChatChannel.create_with_users([create(:user), create(:user)]) ChatChannelMembership.last.update(status: "left_channel") expect(chat_channel.active_users.size).to eq(1) expect(chat_channel.channel_users.size).to eq(1) end end +# rubocop:enable RSpec/MultipleExpectations diff --git a/spec/models/comment_spec.rb b/spec/models/comment_spec.rb index 13386ad6a0980..ff55611a05142 100644 --- a/spec/models/comment_spec.rb +++ b/spec/models/comment_spec.rb @@ -1,3 +1,4 @@ +# rubocop:disable RSpec/ExampleLength, RSpec/MultipleExpectations require "rails_helper" RSpec.describe Comment, type: :model do @@ -5,7 +6,9 @@ let(:article) { create(:article, user_id: user.id, published: true) } let(:comment) { create(:comment, user_id: user.id, commentable_id: article.id) } let(:comment_2) { create(:comment, user_id: user.id, commentable_id: article.id) } - let(:child_comment) { build(:comment, user_id: user.id, commentable_id: article.id, parent_id: comment.id) } + let(:child_comment) do + build(:comment, user_id: user.id, commentable_id: article.id, parent_id: comment.id) + end it "gets proper generated ID code" do expect(comment.id_code_generated).to eq(comment.id.to_s(26)) @@ -114,7 +117,7 @@ end it "shortens long urls" do - comment.body_markdown = "Hello https://longurl.com/dsjkdsdsjdsdskhjdsjbhkdshjdshudsdsbhdsbiudsuidsuidsuidsuidsuidsuidsiudsiudsuidsuisduidsuidsiuiuweuiweuiewuiweuiweuiew?sdhiusduisduidsiudsuidsiusdiusdiuewiuewiuewiuweiuweiuweiuewiuweuiweuiewibsdiubdsiubdsisbdiudsbsdiusdbiu" + comment.body_markdown = "Hello https://longurl.com/dsjkdsdsjdsdskhjdsjbhkdshjdshudsdsbhdsbiudsuidsuidsuidsuidsuidsuidsiudsiudsuidsuisduidsuidsiuiuweuiweuiewuiweuiweuiew?sdhiusduisduidsiudsuidsiusdiusdiuewiuewiuewiuweiuweiuweiuewiuweuiweuiewibsdiubdsiubdsisbdiudsbsdiusdbiu" # rubocop:disable Metrics/LineLength comment.save expect(comment.processed_html.include?("...")).to eq(true) expect(comment.processed_html.size).to be < 450 @@ -186,7 +189,7 @@ expect(ltag_comment.custom_css).not_to eq("") end end - + describe "validity" do it "is invalid if commentable is unpublished article" do article.update_column(:published, false) @@ -197,7 +200,7 @@ describe "#sharemeow_link" do it "uses ShareMeowClient" do - allow(ShareMeowClient).to receive(:image_url).and_return("www.test.com") + allow(ShareMeowClient).to receive(:image_url).and_return("www.test.com") comment.sharemeow_link expect(ShareMeowClient).to have_received(:image_url) end @@ -232,7 +235,9 @@ context "when a comment with ancestor is created" do let(:nest_comment_1) { create(:comment, commentable_id: article.id) } - let(:nest_comment_2) { create(:comment, parent_id: nest_comment_1.id, commentable_id: article.id) } + let(:nest_comment_2) do + create(:comment, parent_id: nest_comment_1.id, commentable_id: article.id) + end let(:author_comment) do create(:comment, parent_id: nest_comment_2.id, commentable_id: article.id, user_id: user.id) @@ -273,3 +278,4 @@ end end end +# rubocop:enable RSpec/ExampleLength, RSpec/MultipleExpectations diff --git a/spec/models/display_ad_spec.rb b/spec/models/display_ad_spec.rb index eeb69c2c55f7f..abe7fbdd1f402 100644 --- a/spec/models/display_ad_spec.rb +++ b/spec/models/display_ad_spec.rb @@ -1,19 +1,19 @@ -require 'rails_helper' +require "rails_helper" RSpec.describe DisplayAd, type: :model do + let(:display_ad) { create(:display_ad, organization_id: organization.id) } + let(:organization) { create(:organization) } + it { is_expected.to validate_presence_of(:organization_id) } it { is_expected.to validate_presence_of(:placement_area) } it { is_expected.to validate_presence_of(:body_markdown) } - let(:organization) { create(:organization) } - let(:display_ad) { create(:display_ad, organization_id: organization.id) } - it "generates processed_html before save" do expect(display_ad.processed_html).to eq("Hello hey Hey hey") end it "only disallows unacceptable placement_area" do display_ad.placement_area = "tsdsdsdds" - expect(display_ad).to_not be_valid + expect(display_ad).not_to be_valid end it "only allows acceptable placement_area" do display_ad.placement_area = "sidebar" diff --git a/spec/models/event_spec.rb b/spec/models/event_spec.rb index ae001bb895e5f..f64afef271bdf 100644 --- a/spec/models/event_spec.rb +++ b/spec/models/event_spec.rb @@ -1,4 +1,4 @@ -require 'rails_helper' +require "rails_helper" RSpec.describe Event, type: :model do let(:event) { create(:event) } diff --git a/spec/models/follow_spec.rb b/spec/models/follow_spec.rb index d27ba2a15ff63..12cbe97ba3960 100644 --- a/spec/models/follow_spec.rb +++ b/spec/models/follow_spec.rb @@ -1,4 +1,4 @@ -require 'rails_helper' +require "rails_helper" RSpec.describe Follow, type: :model do after { StreamRails.enabled = false } @@ -7,9 +7,10 @@ let(:user_2) { create(:user) } before do - StreamRails.enabled = true #Test with StreamRails + StreamRails.enabled = true # Test with StreamRails allow(StreamNotifier).to receive(:new).and_call_original end + it "follows user" do user.follow(user_2) expect(user.following?(user_2)).to eq(true) diff --git a/spec/models/job_opportunity_spec.rb b/spec/models/job_opportunity_spec.rb index 769791b837968..a2496f67d68a7 100644 --- a/spec/models/job_opportunity_spec.rb +++ b/spec/models/job_opportunity_spec.rb @@ -1,4 +1,4 @@ -require 'rails_helper' +require "rails_helper" RSpec.describe JobOpportunity, type: :model do it "returns remoteness in words for remoteness" do diff --git a/spec/models/mention_spec.rb b/spec/models/mention_spec.rb index f2b072b8a9bd2..aac059b8a0259 100644 --- a/spec/models/mention_spec.rb +++ b/spec/models/mention_spec.rb @@ -1,23 +1,32 @@ -require 'rails_helper' +# rubocop:disable RSpec/ExampleLength, RSpec/MultipleExpectations +require "rails_helper" RSpec.describe Mention, type: :model do let(:user) { create(:user) } let(:article) { create(:article, user_id: user.id) } let(:comment) { create(:comment, user_id: user.id, commentable_id: article.id) } + let(:comment2) do + create( + :comment, + body_markdown: "Hello @#{user.username}, you are cool.", + user_id: user.id, + commentable_id: article.id, + ) + end - before(:each) do - #Run workers synchronously + before do + # Run workers synchronously # Delayed::Worker.delay_jobs = false end - it 'creates mention if there is a user mentioned' do + it "creates mention if there is a user mentioned" do comment.body_markdown = "Hello @#{user.username}, you are cool." comment.save Mention.create_all_without_delay(comment) expect(Mention.all.size).to eq(1) end - it 'deletes mention if deleted from comment' do + it "deletes mention if deleted from comment" do comment.body_markdown = "Hello @#{user.username}, you are cool." comment.save Mention.create_all_without_delay(comment) @@ -28,44 +37,42 @@ expect(Mention.all.size).to eq(0) end - it 'creates one mention even if multiple mentions of same user' do - comment.body_markdown = "Hello @#{user.username} @#{user.username} @#{user.username}, you are cool." + it "creates one mention even if multiple mentions of same user" do + comment.body_markdown = "Hello @#{user.username} @#{user.username} @#{user.username}, you rock." comment.save Mention.create_all_without_delay(comment) expect(Mention.all.size).to eq(1) end - it 'creates multiple mentions for multiple users' do - user_2 = create(:user) - comment.body_markdown = "Hello @#{user.username} @#{user_2.username}, you are cool." + it "creates multiple mentions for multiple users" do + user2 = create(:user) + comment.body_markdown = "Hello @#{user.username} @#{user2.username}, you are cool." comment.save Mention.create_all_without_delay(comment) expect(Mention.all.size).to eq(2) end - it 'deletes one of multiple mentions if one of multiple is deleted' do - user_2 = create(:user) - comment.body_markdown = "Hello @#{user.username} @#{user_2.username}, you are cool." + it "deletes one of multiple mentions if one of multiple is deleted" do + user2 = create(:user) + comment.body_markdown = "Hello @#{user.username} @#{user2.username}, you are cool." comment.save Mention.create_all_without_delay(comment) expect(Mention.all.size).to eq(2) - comment.body_markdown = "Hello @#{user_2.username}, you are cool." + comment.body_markdown = "Hello @#{user2.username}, you are cool." comment.save Mention.create_all_without_delay(comment) expect(Mention.all.size).to eq(1) end - it 'creates mention on creation of comment (in addition to update)' do - comment_2 = create(:comment, body_markdown: "Hello @#{user.username}, you are cool.", commentable_id: article.id, user_id:user.id) - Mention.create_all_without_delay(comment_2) + it "creates mention on creation of comment (in addition to update)" do + Mention.create_all_without_delay(comment2) expect(Mention.all.size).to eq(1) end - it "can only be createdwith valid mentionable" do - comment_2 = create(:comment, body_markdown: "Hello @#{user.username}, you are cool.", commentable_id: article.id, user_id:user.id) - comment_2.update_column(:body_markdown, "") - Mention.create_all_without_delay(comment_2) + it "can only be created with valid mentionable" do + comment2.update_column(:body_markdown, "") + Mention.create_all_without_delay(comment2) expect(Mention.all.size).to eq(0) end - end +# rubocop:enable RSpec/ExampleLength, RSpec/MultipleExpectations diff --git a/spec/models/message_spec.rb b/spec/models/message_spec.rb index 6632a2522d82e..34d1184058be2 100644 --- a/spec/models/message_spec.rb +++ b/spec/models/message_spec.rb @@ -1,12 +1,12 @@ require "rails_helper" RSpec.describe Message, type: :model do - let(:user) { create(:user) } - let(:chat_channel) { create(:chat_channel)} + let(:chat_channel) { create(:chat_channel) } + let(:user2) { create(:user) } describe "validations" do - subject { build(:message, :ignore_after_callback)} + subject { build(:message, :ignore_after_callback) } it { is_expected.to belong_to(:user) } it { is_expected.to belong_to(:chat_channel) } @@ -15,13 +15,14 @@ end it "is invalid without channel permission for non-open channels" do - user_2 = create(:user) - chat_channel.channel_type = "invite_only" - chat_channel.save - message = build(:message, chat_channel_id: chat_channel.id, user_id: user_2.id) + chat_channel.update(channel_type: "invite_only") + message = build(:message, chat_channel_id: chat_channel.id, user_id: user2.id) expect(message).not_to be_valid - chat_channel.add_users([user_2]) - message = build(:message, chat_channel_id: chat_channel.id, user_id: user_2.id) + end + + it "is valid with channel permission" do + chat_channel.add_users([user2]) + message = build(:message, chat_channel_id: chat_channel.id, user_id: user2.id) expect(message).to be_valid end diff --git a/spec/models/notification_spec.rb b/spec/models/notification_spec.rb index fc36b56ec3a84..f69c21e2294ca 100644 --- a/spec/models/notification_spec.rb +++ b/spec/models/notification_spec.rb @@ -1,10 +1,10 @@ -require 'rails_helper' +require "rails_helper" RSpec.describe Notification, type: :model do - let(:user) { create(:user) } - let(:user2) { create(:user) } - let(:user3) { create(:user) } - let(:article) { create(:article, user_id: user.id) } + let(:user) { create(:user) } + let(:user2) { create(:user) } + let(:user3) { create(:user) } + let(:article) { create(:article, user_id: user.id) } it "sends notifications to all followers of article user" do user2.follow(user) @@ -13,15 +13,17 @@ expect(Notification.all.size).to eq(2) end + # rubocop:disable RSpec/ExampleLength it "sends sends a broadcast to everyone" do user2.follow(user) user3.follow(user) - broadcast = Broadcast.create!(processed_html: "Hello", - title: "test broadcast", - type_of: "Announcement") + broadcast = Broadcast.create!( + processed_html: "Hello", title: "test broadcast", type_of: "Announcement", + ) Notification.send_all_without_delay(broadcast, "Announcement") expect(Notification.all.size).to eq(3) end + # rubocop:enable RSpec/ExampleLength it "removes all notifications" do user2.follow(user) @@ -30,5 +32,4 @@ Notification.remove_all_without_delay(article, "Published") expect(Notification.all.size).to eq(0) end - -end \ No newline at end of file +end diff --git a/spec/models/podcast_episode_spec.rb b/spec/models/podcast_episode_spec.rb index cb92377c2c425..da2f1e129a027 100644 --- a/spec/models/podcast_episode_spec.rb +++ b/spec/models/podcast_episode_spec.rb @@ -1,9 +1,9 @@ -require 'rails_helper' +require "rails_helper" RSpec.describe PodcastEpisode, type: :model do - let(:podcast) { create(:podcast) } + let(:podcast) { create(:podcast) } - it 'accept valid podcast' do + it "accept valid podcast" do expect(podcast).to be_valid end end diff --git a/spec/models/reaction_spec.rb b/spec/models/reaction_spec.rb index 22df9a4a09fc5..71c4542bf0034 100644 --- a/spec/models/reaction_spec.rb +++ b/spec/models/reaction_spec.rb @@ -1,11 +1,16 @@ +# rubocop:disable RSpec/ExampleLength, RSpec/MultipleExpectations require "rails_helper" RSpec.describe Reaction, type: :model do let(:user) { create(:user) } let(:author) { create(:user) } let(:article) { create(:article, user_id: author.id, featured: true) } - let(:comment) { create(:comment, user_id: user.id, commentable_id: article.id, commentable_type: "Article") } - let(:reaction) { build(:reaction, user_id: user.id, reactable_id: comment.id, reactable_type: "Comment") } + let(:comment) do + create(:comment, user_id: user.id, commentable_id: article.id, commentable_type: "Article") + end + let(:reaction) do + build(:reaction, user_id: user.id, reactable_id: comment.id, reactable_type: "Comment") + end describe "validations" do it "allows like reaction for users without trusted role" do @@ -29,14 +34,18 @@ end it "does not allow reaction on unpublished article" do - reaction = build(:reaction, user_id: user.id, reactable_id: article.id, reactable_type: "Article") + reaction = build( + :reaction, user_id: user.id, reactable_id: article.id, reactable_type: "Article" + ) expect(reaction).to be_valid article.update_column(:published, false) - reaction = build(:reaction, user_id: user.id, reactable_id: article.id, reactable_type: "Article") + reaction = build( + :reaction, user_id: user.id, reactable_id: article.id, reactable_type: "Article" + ) expect(reaction).not_to be_valid end - context "if user is trusted" do + context "when user is trusted" do before { user.add_role(:trusted) } it "allows vomit reactions for users with trusted role" do @@ -77,13 +86,16 @@ describe "stream" do after { StreamRails.enabled = false } + before do StreamRails.enabled = true allow(StreamNotifier).to receive(:new).and_call_original end + it "notifies the reactable author" do - reaction = create(:reaction, user_id: user.id, reactable_id: article.id, reactable_type: "Article") + create(:reaction, user_id: user.id, reactable_id: article.id, reactable_type: "Article") expect(StreamNotifier).to have_received(:new).with(author.id).at_least(:once) end end end +# rubocop:enable RSpec/ExampleLength, RSpec/MultipleExpectations diff --git a/spec/models/search_keyword_spec.rb b/spec/models/search_keyword_spec.rb index 088b06a12a3bd..ee06297e621e8 100644 --- a/spec/models/search_keyword_spec.rb +++ b/spec/models/search_keyword_spec.rb @@ -1,6 +1,8 @@ -require 'rails_helper' +require "rails_helper" RSpec.describe SearchKeyword, type: :model do + let(:search_keyword) { create(:search_keyword) } + it { is_expected.to validate_presence_of(:keyword) } it { is_expected.to validate_presence_of(:google_result_path) } it { is_expected.to validate_presence_of(:google_position) } @@ -8,8 +10,6 @@ it { is_expected.to validate_presence_of(:google_difficulty) } it { is_expected.to validate_presence_of(:google_checked_at) } - let(:search_keyword) { create(:search_keyword) } - it "is valid with proper path" do search_keyword.google_result_path = "/hello/goodbye" expect(search_keyword).to be_valid diff --git a/spec/models/tag_spec.rb b/spec/models/tag_spec.rb index 69805b9d62de6..572c5fa38842d 100644 --- a/spec/models/tag_spec.rb +++ b/spec/models/tag_spec.rb @@ -1,4 +1,4 @@ -require 'rails_helper' +require "rails_helper" RSpec.describe Tag, type: :model do let(:tag) { build(:tag) } diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index 226ad8c13b1a5..b67e164eb2251 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -1,10 +1,11 @@ -require 'rails_helper' +# rubocop:disable RSpec/ExampleLength, RSpec/MultipleExpectations +require "rails_helper" RSpec.describe User, type: :model do let(:user) { create(:user) } let(:returning_user) { create(:user, signup_cta_variant: nil) } let(:second_user) { create(:user) } - let(:article) { create(:article,user_id:user.id) } + let(:article) { create(:article, user_id: user.id) } let(:tag) { create(:tag) } let(:org) { create(:organization) } let (:second_org) { create(:organization) } @@ -38,6 +39,12 @@ # it { is_expected.to have_many(:answers) } # it { is_expected.to validate_uniqueness_of(:email).case_insensitive.allow_blank } + def user_from_authorization_service(service_name, signed_in_resource, cta_variant) + auth = OmniAuth.config.mock_auth[service_name] + service = AuthorizationService.new(auth, signed_in_resource, cta_variant) + service.get_user + end + describe "validations" do it "gets a username after create" do expect(user.username).not_to eq(nil) @@ -114,7 +121,7 @@ end it "does not accept invalid linkedin url" do - user.stackoverflow_url = "ben.com" + user.linkedin_url = "ben.com" expect(user).not_to be_valid end @@ -180,14 +187,14 @@ end it "enforces summary length validation if old summary was valid" do - user.summary = str = "0" * 999 + user.summary = "0" * 999 user.save(validate: false) - user.summary = str = "0" * 999 + user.summary = "0" * 999 expect(user).to be_valid end it "does not inforce summary validation if old summary was invalid" do - user.summary = str = "0" * 999 + user.summary = "0" * 999 expect(user).not_to be_valid end end @@ -196,68 +203,68 @@ describe "user registration" do it "finds user by email and assigns identity to that if exists" do OmniAuth.config.mock_auth[:twitter].info.email = user.email - new_user = AuthorizationService.new(OmniAuth.config.mock_auth[:twitter], nil, "navbar_basic").get_user + + new_user = user_from_authorization_service(:twitter, nil, "navbar_basic") expect(new_user.id).to eq(user.id) end it "assigns random username if username is taken on registration" do OmniAuth.config.mock_auth[:twitter].info.nickname = user.username - new_user = AuthorizationService.new(OmniAuth.config.mock_auth[:twitter], nil, "navbar_basic").get_user + new_user = user_from_authorization_service(:twitter, nil, "navbar_basic") + expect(new_user.persisted?).to eq(true) - expect(new_user.username).to_not eq(user.username) + expect(new_user.username).not_to eq(user.username) end it "assigns random username if username is taken by organization on registration" do org = create(:organization) OmniAuth.config.mock_auth[:twitter].info.nickname = org.slug - new_user = AuthorizationService.new(OmniAuth.config.mock_auth[:twitter], nil, "navbar_basic").get_user + + new_user = user_from_authorization_service(:twitter, nil, "navbar_basic") expect(new_user.persisted?).to eq(true) - expect(new_user.username).to_not eq(org.slug) + expect(new_user.username).not_to eq(org.slug) end - it "assigns signup_cta_variant to state param with Twitter if new user" do - new_user = AuthorizationService.new(OmniAuth.config.mock_auth[:twitter], nil, "hey-hey-hey").get_user + new_user = user_from_authorization_service(:twitter, nil, "hey-hey-hey") expect(new_user.signup_cta_variant).to eq("hey-hey-hey") end it "sets saw_onboarding to false with proper signup variant" do - new_user = AuthorizationService.new(OmniAuth.config.mock_auth[:twitter], nil, "welcome-widget").get_user + new_user = user_from_authorization_service(:twitter, nil, "welcome-widget") expect(new_user.saw_onboarding).to eq(false) end it "sets saw_onboarding to true with nil signup variant" do - new_user = AuthorizationService.new(OmniAuth.config.mock_auth[:twitter], nil, nil).get_user + new_user = user_from_authorization_service(:twitter, nil, nil) expect(new_user.saw_onboarding).to eq(true) end - - it "does not assign signup_cta_variant to non-new users" do - new_user = AuthorizationService.new(OmniAuth.config.mock_auth[:twitter], returning_user, "hey-hey-hey").get_user + new_user = user_from_authorization_service(:twitter, returning_user, "hey-hey-hey") expect(new_user.signup_cta_variant).to eq(nil) end it "assigns proper social_username based on auth" do OmniAuth.config.mock_auth[:twitter].info.nickname = "valid_username" - new_user = AuthorizationService.new(OmniAuth.config.mock_auth[:twitter], nil, "navbar_basic").get_user + new_user = user_from_authorization_service(:twitter, nil, "navbar_basic") expect(new_user.username).to eq("valid_username") end it "assigns modified username if invalid" do OmniAuth.config.mock_auth[:twitter].info.nickname = "invalid.username" - new_user = AuthorizationService.new(OmniAuth.config.mock_auth[:twitter], nil, "navbar_basic").get_user + new_user = user_from_authorization_service(:twitter, nil, "navbar_basic") expect(new_user.username).to eq("invalidusername") end it "assigns an identity to user" do - new_user = AuthorizationService.new(OmniAuth.config.mock_auth[:twitter], nil, "navbar_basic").get_user + new_user = user_from_authorization_service(:twitter, nil, "navbar_basic") expect(new_user.identities.size).to eq(1) - new_user = AuthorizationService.new(OmniAuth.config.mock_auth[:github], nil, "navbar_basic").get_user + new_user = user_from_authorization_service(:github, nil, "navbar_basic") expect(new_user.identities.size).to eq(2) - new_user = AuthorizationService.new(OmniAuth.config.mock_auth[:twitter], nil, "navbar_basic").get_user + new_user = user_from_authorization_service(:twitter, nil, "navbar_basic") expect(new_user.identities.size).to eq(2) - new_user = AuthorizationService.new(OmniAuth.config.mock_auth[:github], nil, "navbar_basic").get_user + new_user = user_from_authorization_service(:github, nil, "navbar_basic") expect(new_user.identities.size).to eq(2) end @@ -271,25 +278,26 @@ expect(user.estimated_default_language).to eq("ja") end it "estimates default language based on ID dump" do - new_user = AuthorizationService.new(OmniAuth.config.mock_auth[:twitter], nil, "navbar_basic").get_user + new_user = user_from_authorization_service(:twitter, nil, "navbar_basic") new_user.estimate_default_language_without_delay! end end it "follows users" do - user_2 = create(:user) - user_3 = create(:user) - user.follow(user_2) - user.follow(user_3) + user2 = create(:user) + user3 = create(:user) + user.follow(user2) + user.follow(user3) expect(user.all_follows.size).to eq(2) end - describe '#followed_articles' do - let(:user_2) { create(:user) } - let(:user_3) { create(:user) } + describe "#followed_articles" do + let(:user2) { create(:user) } + let(:user3) { create(:user) } + before do - 3.times { create(:article, user_id: user_2.id) } - user.follow(user_2) + create_list(:article, 3, user_id: user2.id) + user.follow(user2) end it "returns all articles following" do @@ -310,7 +318,7 @@ expect(user).not_to be_valid end - it "does not allow to change to username that is taken" do + it "does not allow to change to username that is taken by an organization" do user.username = create(:organization).slug expect(user).not_to be_valid end @@ -326,30 +334,32 @@ expect(user.score).to be > 0 end - it 'persists JSON dump of identity data' do - new_user = AuthorizationService.new(OmniAuth.config.mock_auth[:twitter], nil, "navbar_basic").get_user + it "persists JSON dump of identity data" do + new_user = user_from_authorization_service(:twitter, nil, "navbar_basic") identity = new_user.identities.first expect(identity.auth_data_dump.provider).to eq(identity.provider) end - it 'persists extracts relevant identity data from logged in user' do - new_user = AuthorizationService.new(OmniAuth.config.mock_auth[:twitter], nil, "navbar_basic").get_user + it "persists extracts relevant identity data from logged in user" do + new_user = user_from_authorization_service(:twitter, nil, "navbar_basic") expect(new_user.twitter_following_count).to be_an(Integer) expect(new_user.twitter_followers_count).to eq(100) expect(new_user.twitter_created_at).to be_kind_of(ActiveSupport::TimeWithZone) - new_user = AuthorizationService.new(OmniAuth.config.mock_auth[:github], nil, "navbar_basic").get_user + new_user = user_from_authorization_service(:github, nil, "navbar_basic") expect(new_user.github_created_at).to be_kind_of(ActiveSupport::TimeWithZone) end describe "onboarding checklist" do it "returns onboarding checklist made first article if made first published article" do article.update(published: true) - expect(UserStates.new(user).cached_onboarding_checklist[:write_your_first_article]).to eq(true) + checklist = UserStates.new(user).cached_onboarding_checklist[:write_your_first_article] + expect(checklist).to eq(true) end it "returns onboarding checklist made first article false if hasn't written article" do article.update(published: false) - expect(UserStates.new(user).cached_onboarding_checklist[:write_your_first_article]).to eq(true) + checklist = UserStates.new(user).cached_onboarding_checklist[:write_your_first_article] + expect(checklist).to eq(true) end it "returns onboarding checklist follow_your_first_tag if has followed tag" do @@ -373,20 +383,24 @@ it "returns onboarding checklist leave_your_first_reaction if has reacted to a post" do create(:reaction, user_id: user.id, reactable_id: article.id) - expect(UserStates.new(user).cached_onboarding_checklist[:leave_your_first_reaction]).to eq(true) + checklist = UserStates.new(user).cached_onboarding_checklist[:leave_your_first_reaction] + expect(checklist).to eq(true) end - it "returns onboarding checklist leave_your_first_reaction false if has not reacted to a post" do - expect(UserStates.new(user).cached_onboarding_checklist[:leave_your_first_reaction]).to eq(false) + it "returns onboarding checklist leave_your_first_reaction false if hasn't reacted to a post" do + checklist = UserStates.new(user).cached_onboarding_checklist[:leave_your_first_reaction] + expect(checklist).to eq(false) end it "returns onboarding checklist leave_your_first_comment if has left comment" do create(:comment, user_id: user.id, commentable_id: article.id, commentable_type: "Article") - expect(UserStates.new(user).cached_onboarding_checklist[:leave_your_first_comment]).to eq(true) + checklist = UserStates.new(user).cached_onboarding_checklist[:leave_your_first_comment] + expect(checklist).to eq(true) end it "returns onboarding checklist leave_your_first_comment false if has not left comment" do - expect(UserStates.new(user).cached_onboarding_checklist[:leave_your_first_comment]).to eq(false) + checklist = UserStates.new(user).cached_onboarding_checklist[:leave_your_first_comment] + expect(checklist).to eq(false) end end @@ -444,3 +458,4 @@ end end end +# rubocop:enable RSpec/ExampleLength, RSpec/MultipleExpectations diff --git a/spec/policies/admin_policy_spec.rb b/spec/policies/admin_policy_spec.rb index 2119fa3e916aa..65235d89893d9 100644 --- a/spec/policies/admin_policy_spec.rb +++ b/spec/policies/admin_policy_spec.rb @@ -4,17 +4,19 @@ subject { described_class } permissions :show? do - context "non admin" do - let(:user) {build(:user)} - it "should not allow someone without admin privileges to do continue" do - expect(subject).not_to permit(user) + context "when regular user" do + let(:user) { build(:user) } + + it "does not allow someone without admin privileges to do continue" do + expect(subject).not_to permit(user) # rubocop:disable RSpec/NamedSubject end end - context "admin" do - let(:user) {build(:user, :super_admin)} + context "when admin" do + let(:user) { build(:user, :super_admin) } + it "allow someone with admin privileges to continue" do - expect(subject).to permit(user) + expect(subject).to permit(user) # rubocop:disable RSpec/NamedSubject end end end diff --git a/spec/policies/chat_channel_membership_policy_spec.rb b/spec/policies/chat_channel_membership_policy_spec.rb index afa75a17b4f58..b53a9396588e1 100644 --- a/spec/policies/chat_channel_membership_policy_spec.rb +++ b/spec/policies/chat_channel_membership_policy_spec.rb @@ -5,23 +5,30 @@ let(:chat_channel_membership) { build(:chat_channel_membership) } - context "when user is not signed-in" do let(:user) { nil } + it { within_block_is_expected.to raise_error(Pundit::NotAuthorizedError) } end context "when user belongs to membership" do let(:user) { create(:user) } - let(:chat_channel) { create(:chat_channel ) } - let(:chat_channel_membership) { create(:chat_channel_membership, user_id: user.id, chat_channel_id: chat_channel.id ) } + let(:chat_channel) { create(:chat_channel) } + let(:chat_channel_membership) do + create(:chat_channel_membership, user_id: user.id, chat_channel_id: chat_channel.id) + end + it { is_expected.to permit_actions(%i[update destroy]) } end + context "when user does not belong to membership" do let(:user) { create(:user) } let(:other_user) { create(:user) } - let(:chat_channel) { create(:chat_channel ) } - let(:chat_channel_membership) { create(:chat_channel_membership, user_id: other_user.id, chat_channel_id: chat_channel.id ) } + let(:chat_channel) { create(:chat_channel) } + let(:chat_channel_membership) do + create(:chat_channel_membership, user_id: other_user.id, chat_channel_id: chat_channel.id) + end + it { is_expected.to forbid_actions(%i[update destroy]) } end -end \ No newline at end of file +end diff --git a/spec/policies/chat_channel_policy_spec.rb b/spec/policies/chat_channel_policy_spec.rb index 42e32dd0418fe..076463434c5bf 100644 --- a/spec/policies/chat_channel_policy_spec.rb +++ b/spec/policies/chat_channel_policy_spec.rb @@ -13,20 +13,25 @@ context "when user is not a part of channel" do let(:user) { build(:user) } + it { is_expected.to permit_actions(%i[index]) } it { is_expected.to forbid_actions(%i[show open moderate update]) } end context "when user is a part of channel" do let(:user) { create(:user) } + before { chat_channel.add_users [user] } + it { is_expected.to permit_actions(%i[index show open]) } it { is_expected.to forbid_actions(%i[moderate update]) } end context "when user is an admin but not part of channel" do let(:user) { create(:user) } + before { user.add_role(:super_admin) } + it { is_expected.to permit_actions(%i[index moderate update]) } it { is_expected.to forbid_actions(%i[show open]) } end diff --git a/spec/policies/comment_policy_spec.rb b/spec/policies/comment_policy_spec.rb index 3ce76db76639a..0391bc0097774 100644 --- a/spec/policies/comment_policy_spec.rb +++ b/spec/policies/comment_policy_spec.rb @@ -25,7 +25,9 @@ it { is_expected.to permit_actions(%i[create]) } it { is_expected.to forbid_actions(%i[edit update destroy delete_confirm]) } - it { is_expected.to permit_mass_assignment_of(valid_attributes_for_create).for_action(:create) } + it do + is_expected.to permit_mass_assignment_of(valid_attributes_for_create).for_action(:create) + end context "with banned status" do before { user.add_role :banned } @@ -48,7 +50,9 @@ it { is_expected.to permit_actions(%i[edit update destroy delete_confirm]) } it { is_expected.to forbid_actions(%i[create]) } - it { is_expected.to permit_mass_assignment_of(valid_attributes_for_update).for_action(:update) } + it do + is_expected.to permit_mass_assignment_of(valid_attributes_for_update).for_action(:update) + end end end end diff --git a/spec/policies/image_upload_policy_spec.rb b/spec/policies/image_upload_policy_spec.rb index 09576ad0b4c4b..ad1bf2ed54783 100644 --- a/spec/policies/image_upload_policy_spec.rb +++ b/spec/policies/image_upload_policy_spec.rb @@ -2,7 +2,7 @@ RSpec.describe ImageUploadPolicy do subject { described_class.new(user, image) } - + let(:image) { "📸.jpg" } context "when user is not signed in" do diff --git a/spec/policies/reaction_policy_spec.rb b/spec/policies/reaction_policy_spec.rb index ea28356d9d49b..2c1d80cf893be 100644 --- a/spec/policies/reaction_policy_spec.rb +++ b/spec/policies/reaction_policy_spec.rb @@ -17,10 +17,9 @@ it { is_expected.to permit_actions(%i[index create]) } context "when user is banned" do let(:user) { build(:user, :banned) } - + it { is_expected.to permit_actions(%i[index]) } it { is_expected.to forbid_actions(%i[create]) } end end - end diff --git a/spec/policies/user_policy_spec.rb b/spec/policies/user_policy_spec.rb index 41dcad00d07ac..10bc161da0665 100644 --- a/spec/policies/user_policy_spec.rb +++ b/spec/policies/user_policy_spec.rb @@ -14,7 +14,11 @@ context "when user is signed-in" do let(:user) { other_user } - it { is_expected.to permit_actions(%i[edit update onboarding_update join_org leave_org dashboard_show]) } + it do + is_expected.to permit_actions( + %i[edit update onboarding_update join_org leave_org dashboard_show], + ) + end context "with banned status" do before { user.add_role(:banned) } diff --git a/spec/policies/video_policy_spec.rb b/spec/policies/video_policy_spec.rb index d0f7c47c60a4d..2343e29f221c1 100644 --- a/spec/policies/video_policy_spec.rb +++ b/spec/policies/video_policy_spec.rb @@ -1,22 +1,27 @@ -require 'rails_helper' +require "rails_helper" RSpec.describe VideoPolicy do subject { described_class.new(user, nil) } + let(:user) { User.new } context "when user is not signed-in" do let(:user) { nil } + it { within_block_is_expected.to raise_error(Pundit::NotAuthorizedError) } end context "when user does not have video permission" do let(:user) { build(:user) } + it { is_expected.to forbid_actions(%i[new create]) } end context "when user does not have video permission" do let(:user) { build(:user) } + before { user.add_role :video_permission } + it { is_expected.to permit_actions(%i[new create]) } end end diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb index 99f7678661aa6..351b610fbbd10 100644 --- a/spec/rails_helper.rb +++ b/spec/rails_helper.rb @@ -1,7 +1,7 @@ # This file is copied to spec/ when you run 'rails generate rspec:install' ENV["RAILS_ENV"] = "test" -require File.expand_path("../../config/environment", __FILE__) +require File.expand_path("../config/environment", __dir__) require "rspec/rails" Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f } @@ -46,8 +46,8 @@ # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures config.fixture_path = "#{::Rails.root}/spec/fixtures" - Approvals.configure do |config| - config.approvals_path = "#{::Rails.root}/spec/support/fixtures/approvals/" + Approvals.configure do |approvals_config| + approvals_config.approvals_path = "#{::Rails.root}/spec/support/fixtures/approvals/" end config.include Devise::Test::ControllerHelpers, type: :view @@ -77,7 +77,7 @@ end # Only turn on VCR if :vcr is included metadata keys - config.around(:each) do |ex| + config.around do |ex| if ex.metadata.key?(:vcr) ex.run else @@ -92,27 +92,27 @@ puts "Running **live** tests against Stripe..." end - config.before(:each) do - stub_request(:any, /res.cloudinary.com/).to_rack('dsdsdsds') + config.before do + stub_request(:any, /res.cloudinary.com/).to_rack("dsdsdsds") stub_request(:post, /api.fastly.com/). - with(headers: { 'Fastly-Key' => 'f15066a3abedf47238b08e437684c84f' }). - to_return(status: 200, body: '', headers: {}) + with(headers: { "Fastly-Key" => "f15066a3abedf47238b08e437684c84f" }). + to_return(status: 200, body: "", headers: {}) stub_request(:post, /api.bufferapp.com/). - to_return(status: 200, body: {fake_text:"so fake"}.to_json, headers: {}) + to_return(status: 200, body: { fake_text: "so fake" }.to_json, headers: {}) # stub_request(:any, /api.getstream.io/).to_rack(FakeStream) # for twitter image cdn - stub_request(:get, /twimg.com/) - .to_return(status: 200, body: '', headers: {}) + stub_request(:get, /twimg.com/). + to_return(status: 200, body: "", headers: {}) - stub_request(:any, /api.mailchimp.com/) - .to_return(status: 200, body: '', headers: {}) + stub_request(:any, /api.mailchimp.com/). + to_return(status: 200, body: "", headers: {}) - stub_request(:post, /us-east-api.stream-io-api.com\/api\/v1.0\/feed\/user/) - .to_return(status: 200, body: '{}', headers: {}) + stub_request(:post, /us-east-api.stream-io-api.com\/api\/v1.0\/feed\/user/). + to_return(status: 200, body: "{}", headers: {}) stub_request(:get, /us-east-api.stream-io-api.com\/api/).to_rack(FakeStream) end @@ -129,7 +129,7 @@ raw_info.first_name = "fname" raw_info.gender = "female" raw_info.id = "123456" - raw_info.last_name ="lname" + raw_info.last_name = "lname" raw_info.link = "http://www.facebook.com/url”" raw_info.lang = "fr" raw_info.locale = "en_US" diff --git a/spec/requests/additional_content_boxes_spec.rb b/spec/requests/additional_content_boxes_spec.rb index 044ac1adf1fbb..ad37c8b9915c6 100644 --- a/spec/requests/additional_content_boxes_spec.rb +++ b/spec/requests/additional_content_boxes_spec.rb @@ -17,10 +17,11 @@ get "/additional_content_boxes?article_id=#{regular_article.id}" expect(response.body).not_to include CGI.escapeHTML(suggestion.title) end + it "returns boosted article if available" do organization = create(:organization) - suggestion = create(:article, published: true, featured: true) - boosted_sugg = create(:article, tags: [tag.name], featured: true, boosted_additional_articles: true, organization_id: organization.id) + create(:article, published: true, featured: true) + boosted_sugg = create(:article, tags: [tag.name], featured: true, boosted_additional_articles: true, organization_id: organization.id) # rubocop:disable Metrics/LineLength get "/additional_content_boxes?article_id=#{regular_article.id}" expect(response.body).to include CGI.escapeHTML(boosted_sugg.title) end diff --git a/spec/requests/articles_api_spec.rb b/spec/requests/articles_api_spec.rb index db7964a8069da..76dcc8ca698f2 100644 --- a/spec/requests/articles_api_spec.rb +++ b/spec/requests/articles_api_spec.rb @@ -1,11 +1,15 @@ require "rails_helper" RSpec.describe "ArticlesApi", type: :request do + let(:user1) { create(:user) } + let(:user2) { create(:user) } + describe "GET /api/articles" do it "returns json response" do get "/api/articles" expect(response.content_type).to eq("application/json") end + it "returns featured articles with no params" do create(:article) create(:article, featured: true) @@ -13,19 +17,18 @@ get "/api/articles" expect(JSON.parse(response.body).size).to eq(2) end + it "returns user articles if username param is present" do - user1 = create(:user) - user2 = create(:user) create(:article, user_id: user1.id) create(:article, user_id: user1.id) create(:article, user_id: user2.id) get "/api/articles?username=#{user1.username}" expect(JSON.parse(response.body).size).to eq(2) end + + # rubocop:disable RSpec/ExampleLength it "returns organization articles if username param is present" do org = create(:organization) - user1 = create(:user) - user2 = create(:user) create(:article, user_id: user1.id) create(:article, user_id: user1.id, organization_id: org.id) create(:article, user_id: user1.id, organization_id: org.id) @@ -34,16 +37,18 @@ get "/api/articles?username=#{org.slug}" expect(JSON.parse(response.body).size).to eq(2) end + # rubocop:enable RSpec/ExampleLength + it "returns tag articles if tag param is present" do article = create(:article) get "/api/articles?tag=#{article.tag_list.first}" expect(JSON.parse(response.body).size).to eq(1) end - it "returns tag articles if tag param is present" do + + it "returns not tag articles if article and tag are not approved" do article = create(:article, approved: false) tag = Tag.find_by_name(article.tag_list.first) - tag.requires_approval = true - tag.save + tag.update(requires_approval: true) get "/api/articles?tag=#{tag.name}" expect(JSON.parse(response.body).size).to eq(0) end diff --git a/spec/requests/articles_create_spec.rb b/spec/requests/articles_create_spec.rb index 8e828409d9c41..b6492a6829280 100644 --- a/spec/requests/articles_create_spec.rb +++ b/spec/requests/articles_create_spec.rb @@ -15,32 +15,40 @@ expect(Article.last.user_id).to eq(user.id) end + # rubocop:disable RSpec/ExampleLength it "creates article with front matter params" do - new_title = "NEW TITLE #{rand(100)}" post "/articles", params: { - article: { body_markdown: "---\ntitle: hey hey hahuu\npublished: false\n---\nYo ho ho#{rand(100)}", tag_list: "yo" }, + article: { + body_markdown: "---\ntitle: hey hey hahuu\npublished: false\n---\nYo ho ho#{rand(100)}", + tag_list: "yo", + }, } expect(Article.last.title).to eq("hey hey hahuu") end it "does not allow job opportunity job to not include hiring tag" do new_title = "NEW TITLE #{rand(100)}" - expect{ post "/articles", params: { - article: { - title: new_title, body_markdown: "Yo ho ho#{rand(100)}", tag_list: "yoyo", - job_opportunity: { remoteness: "on_premise" } - }, - }}.to raise_error(RuntimeError) + expect do + post "/articles", params: { + article: { + title: new_title, + body_markdown: "Yo ho ho#{rand(100)}", tag_list: "yoyo", + job_opportunity: { remoteness: "on_premise" } + }, + } + end .to raise_error(RuntimeError) end it "creates article with job opportunity nested" do new_title = "NEW TITLE #{rand(100)}" post "/articles", params: { article: { - title: new_title, body_markdown: "Yo ho ho#{rand(100)}", tag_list: "hiring", + title: new_title, + body_markdown: "Yo ho ho#{rand(100)}", tag_list: "hiring", job_opportunity: { remoteness: "on_premise" } }, } expect(Article.last.job_opportunity.remoteness).to eq("on_premise") end + # rubocop:enable RSpec/ExampleLength end diff --git a/spec/requests/articles_update_spec.rb b/spec/requests/articles_update_spec.rb index 489e35c2726cf..4ae63e3defcb1 100644 --- a/spec/requests/articles_update_spec.rb +++ b/spec/requests/articles_update_spec.rb @@ -16,6 +16,7 @@ expect(Article.last.title).to eq(new_title) end + # rubocop:disable RSpec/ExampleLength it "does not create a job opportunity if no hiring tag" do new_title = "NEW TITLE #{rand(100)}" put "/articles/#{article.id}", params: { @@ -27,7 +28,6 @@ expect(JobOpportunity.count).to eq(0) end - it "updates ordinary article with job opportunity nested" do new_title = "NEW TITLE #{rand(100)}" put "/articles/#{article.id}", params: { @@ -38,5 +38,5 @@ } expect(Article.last.job_opportunity.remoteness).to eq("on_premise") end - + # rubocop:enable RSpec/ExampleLength end diff --git a/spec/requests/async_info_spec.rb b/spec/requests/async_info_spec.rb index 0bd8fe98ef695..bb86950a05383 100644 --- a/spec/requests/async_info_spec.rb +++ b/spec/requests/async_info_spec.rb @@ -2,17 +2,35 @@ RSpec.describe "AsyncInfo", type: :request do let(:user) { build(:user) } + describe "GET /async_info/base_data" do - it "returns token and no user for non-logged-in" do - get "/async_info/base_data" - expect(response.body).to include("token") - expect(response.body).not_to include("user") + describe "anonymous user" do + before do + get "/async_info/base_data" + end + + it "returns token" do + expect(response.body).to include("token") + end + + it "does not return user" do + expect(response.body).not_to include("user") + end end - it "returns token and no user for non-logged-in" do - sign_in user - get "/async_info/base_data" - expect(response.body).to include("token") - expect(response.body).to include("user") + + describe "logged in user" do + before do + sign_in user + get "/async_info/base_data" + end + + it "returns token" do + expect(response.body).to include("token") + end + + it "does return user" do + expect(response.body).to include("user") + end end end end diff --git a/spec/requests/blocks_spec.rb b/spec/requests/blocks_spec.rb index b37be0fead095..4bc71d0bd9eec 100644 --- a/spec/requests/blocks_spec.rb +++ b/spec/requests/blocks_spec.rb @@ -13,25 +13,32 @@ end end + # rubocop:disable RSpec/ExampleLength describe "POST blocks" do it "creates block from input data" do post "/blocks", params: { - block: { input_css: ".blue { color: blue;}", input_html: "yo", input_javascript: "alert('hey')" }, + block: { + input_css: ".blue { color: blue;}", + input_html: "yo", + input_javascript: "alert('hey')", + }, } expect(Block.all.size).to eq(1) end end + describe "PUT blocks" do it "updates block from input data" do block = create(:block, user_id: user.id, input_css: ".blue { color: blue;}") put "/blocks/#{block.id}", params: { block: { input_css: ".blue { color: red;}", - input_html: "yo", - input_javascript: "alert('hey')" }, + input_html: "yo", + input_javascript: "alert('hey')" }, } expect(Block.last.processed_css).to include("color: red") end end + # rubocop:enable RSpec/ExampleLength describe "DELETE blocks" do it "updates block from input data" do diff --git a/spec/requests/chat_channel_memberships_spec.rb b/spec/requests/chat_channel_memberships_spec.rb index 254d5dc047dbb..5f75905ec80fa 100644 --- a/spec/requests/chat_channel_memberships_spec.rb +++ b/spec/requests/chat_channel_memberships_spec.rb @@ -1,3 +1,4 @@ +# rubocop:disable RSpec/ExampleLength, RSpec/MultipleExpectations require "rails_helper" RSpec.describe "ChatChannelMemberships", type: :request do @@ -16,17 +17,20 @@ mems_num = ChatChannelMembership.all.size post "/chat_channel_memberships", params: { chat_channel_membership: { - user_id: second_user.id, chat_channel_id: chat_channel.id} - } + user_id: second_user.id, chat_channel_id: chat_channel.id + }, + } expect(ChatChannelMembership.all.size).to eq(mems_num + 1) expect(ChatChannelMembership.last.status).to eq("pending") end + it "denies chat channel invitation to non-authorized user" do expect do post "/chat_channel_memberships", params: { chat_channel_membership: { - user_id: second_user.id, chat_channel_id: chat_channel.id} - } + user_id: second_user.id, chat_channel_id: chat_channel.id + }, + } end.to raise_error(Pundit::NotAuthorizedError) end end @@ -35,28 +39,36 @@ before do user.add_role(:super_admin) post "/chat_channel_memberships", params: { - chat_channel_membership: {user_id: second_user.id, chat_channel_id: chat_channel.id}} + chat_channel_membership: { user_id: second_user.id, chat_channel_id: chat_channel.id }, + } end + it "accepts chat channel invitation" do membership = ChatChannelMembership.last sign_in second_user put "/chat_channel_memberships/#{membership.id}", params: { chat_channel_membership: { - user_action: "accept"}} + user_action: "accept", + }, + } expect(ChatChannelMembership.find(membership.id).status).to eq("active") end + it "rejects chat channel invitation" do membership = ChatChannelMembership.last sign_in second_user put "/chat_channel_memberships/#{membership.id}", params: { - chat_channel_membership: {user_action: "reject"}} + chat_channel_membership: { user_action: "reject" }, + } expect(ChatChannelMembership.find(membership.id).status).to eq("rejected") end + it "disallows non-logged-user" do membership = ChatChannelMembership.last expect do put "/chat_channel_memberships/#{membership.id}", params: { - chat_channel_membership: {user_action: "accept"}} + chat_channel_membership: { user_action: "accept" }, + } expect(ChatChannelMembership.find(membership.id).status).to eq("active") end.to raise_error(Pundit::NotAuthorizedError) end @@ -66,8 +78,10 @@ before do user.add_role(:super_admin) post "/chat_channel_memberships", params: { - chat_channel_membership: {user_id: second_user.id, chat_channel_id: chat_channel.id}} + chat_channel_membership: { user_id: second_user.id, chat_channel_id: chat_channel.id }, + } end + it "leaves chat channel" do membership = ChatChannelMembership.last sign_in second_user @@ -76,3 +90,4 @@ end end end +# rubocop:enable RSpec/ExampleLength, RSpec/MultipleExpectations diff --git a/spec/requests/chat_channels_spec.rb b/spec/requests/chat_channels_spec.rb index ecde241a12024..69e697412df3d 100644 --- a/spec/requests/chat_channels_spec.rb +++ b/spec/requests/chat_channels_spec.rb @@ -5,7 +5,9 @@ let(:test_subject) { create(:user) } let(:chat_channel) { create(:chat_channel) } let(:invite_channel) { create(:chat_channel, channel_type: "invite_only") } - let(:direct_channel) { create(:chat_channel, channel_type: "direct", slug: "hello/#{user.username}") } + let(:direct_channel) do + create(:chat_channel, channel_type: "direct", slug: "hello/#{user.username}") + end before do sign_in user @@ -13,7 +15,7 @@ end describe "GET /connect" do - context "logged in" do + context "when logged in" do before do get "/connect" end @@ -23,7 +25,7 @@ end end - context "logged in, visiting existing channel" do + context "when logged in and visiting existing channel" do before do invite_channel.add_users [user] sign_in user @@ -39,10 +41,7 @@ describe "get /chat_channels?state=unopened" do it "returns unopened channels" do direct_channel.add_users [user] - user.chat_channel_memberships.each do |m| - m.has_unopened_messages = true - m.save - end + user.chat_channel_memberships.each { |m| m.update(has_unopened_messages: true) } sign_in user get "/chat_channels?state=unopened" expect(response.body).to include(direct_channel.slug) @@ -51,27 +50,26 @@ describe "get /chat_channels?state=pending" do it "returns pending channels" do - pending_membership = ChatChannelMembership.create(chat_channel_id: invite_channel.id, - user_id:user.id, status: "pending") + ChatChannelMembership.create(chat_channel_id: invite_channel.id, user_id: user.id, status: "pending") # rubocop:disable Metrics/LineLength sign_in user get "/chat_channels?state=pending" expect(response.body).to include(invite_channel.slug) end + it "returns no pending channels if no invites" do sign_in user get "/chat_channels?state=pending" expect(response.body).not_to include(invite_channel.slug) end + it "returns no pending channels if not pending" do - pending_membership = ChatChannelMembership.create(chat_channel_id: invite_channel.id, - user_id:user.id, status: "rejected") + ChatChannelMembership.create(chat_channel_id: invite_channel.id, user_id: user.id, status: "rejected") # rubocop:disable Metrics/LineLength sign_in user get "/chat_channels?state=pending" expect(response.body).not_to include(invite_channel.slug) end end - describe "GET /chat_channels/:id" do context "when request is valid" do before do @@ -95,18 +93,21 @@ end describe "POST /chat_channels" do + # rubocop:disable RSpec/MultipleExpectations it "creates chat_channel for current user" do post "/chat_channels", - params: { chat_channel: { channel_name: "Hello Channel", slug: "hello-channel" } }, - headers: { HTTP_ACCEPT: "application/json" } + params: { chat_channel: { channel_name: "Hello Channel", slug: "hello-channel" } }, + headers: { HTTP_ACCEPT: "application/json" } expect(ChatChannel.last.slug).to eq("hello-channel") expect(ChatChannel.last.active_users).to include(user) end + # rubocop:enable RSpec/MultipleExpectations + it "returns errors if channel is invalid" do - #slug should be taken + # slug should be taken post "/chat_channels", - params: { chat_channel: { channel_name: "HEy hey hoho", slug: chat_channel.slug } }, - headers: { HTTP_ACCEPT: "application/json" } + params: { chat_channel: { channel_name: "HEy hey hoho", slug: chat_channel.slug } }, + headers: { HTTP_ACCEPT: "application/json" } expect(response.body).to include("Slug has already been taken") end end @@ -115,23 +116,23 @@ it "updates channel for valid user" do user.add_role(:super_admin) put "/chat_channels/#{chat_channel.id}", - params: { chat_channel: { channel_name: "Hello Channel", slug: "hello-channelly" } }, - headers: { HTTP_ACCEPT: "application/json" } + params: { chat_channel: { channel_name: "Hello Channel", slug: "hello-channelly" } }, + headers: { HTTP_ACCEPT: "application/json" } expect(ChatChannel.last.slug).to eq("hello-channelly") end it "dissallows invalid users" do expect do put "/chat_channels/#{chat_channel.id}", - params: { chat_channel: { channel_name: "Hello Channel", slug: "hello-channelly" } }, - headers: { HTTP_ACCEPT: "application/json" } + params: { chat_channel: { channel_name: "Hello Channel", slug: "hello-channelly" } }, + headers: { HTTP_ACCEPT: "application/json" } end.to raise_error(Pundit::NotAuthorizedError) end it "returns errors if channel is invalid" do - #slug should be taken + # slug should be taken user.add_role(:super_admin) put "/chat_channels/#{chat_channel.id}", - params: { chat_channel: { channel_name: "HEy hey hoho", slug: invite_channel.slug } }, - headers: { HTTP_ACCEPT: "application/json" } + params: { chat_channel: { channel_name: "HEy hey hoho", slug: invite_channel.slug } }, + headers: { HTTP_ACCEPT: "application/json" } expect(response.body).to include("Slug has already been taken") end end @@ -145,6 +146,7 @@ end.to raise_error(Pundit::NotAuthorizedError) end + # rubocop:disable RSpec/ExampleLength it "raises NotAuthorizedError if user is logged in but not authorized" do sign_in user expect do @@ -153,6 +155,7 @@ headers: { HTTP_ACCEPT: "application/json" } end.to raise_error(Pundit::NotAuthorizedError) end + # rubocop:enable RSpec/ExampleLength context "when user is logged-in and authorized" do before do @@ -161,12 +164,13 @@ allow(Pusher).to receive(:trigger).and_return(true) end - it "enforces chat_channel_params" do + it "enforces chat_channel_params on ban" do post "/chat_channels/#{chat_channel.id}/moderate", params: { chat_channel: { command: "/ban #{test_subject.username}" } } expect(response.status).to eq(200) end - it "enforces chat_channel_params" do + + it "enforces chat_channel_params on unban" do post "/chat_channels/#{chat_channel.id}/moderate", params: { chat_channel: { command: "/unban #{test_subject.username}" } } expect(response.status).to eq(200) diff --git a/spec/requests/comments_api_spec.rb b/spec/requests/comments_api_spec.rb index 60c57bc4233a5..6c4a67759fa50 100644 --- a/spec/requests/comments_api_spec.rb +++ b/spec/requests/comments_api_spec.rb @@ -2,18 +2,20 @@ require "rails_helper" RSpec.describe "ArticlesApi", type: :request do + let(:article) { create(:article) } + before do - @article = FactoryBot.create(:article) - FactoryBot.create(:comment, commentable_type: "Article", commentable_id: @article.id) - FactoryBot.create(:comment, commentable_type: "Article", commentable_id: @article.id) + FactoryBot.create(:comment, commentable_type: "Article", commentable_id: article.id) + FactoryBot.create(:comment, commentable_type: "Article", commentable_id: article.id) end + describe "GET /api/comments" do it "returns not found if inproper article id" do - expect { get "/api/comments?a_id=gobbledygook" }. - to raise_error(ActiveRecord::RecordNotFound) + expect { get "/api/comments?a_id=gobbledygook" }.to raise_error(ActiveRecord::RecordNotFound) end + it "returns comments for article passed" do - get "/api/comments?a_id=#{@article.id}" + get "/api/comments?a_id=#{article.id}" expect(JSON.parse(response.body).size).to eq(2) end end diff --git a/spec/requests/comments_spec.rb b/spec/requests/comments_spec.rb index 15519fc317142..e2e46b09e63e8 100644 --- a/spec/requests/comments_spec.rb +++ b/spec/requests/comments_spec.rb @@ -65,7 +65,9 @@ describe "POST /comments/preview" do it "returns 401 if user is not logged in" do - post "/comments/preview", params: { comment: { body_markdown: "hi"}}, headers: { HTTP_ACCEPT: "application/json" } + post "/comments/preview", + params: { comment: { body_markdown: "hi" } }, + headers: { HTTP_ACCEPT: "application/json" } expect(response).to have_http_status(401) end diff --git a/spec/requests/dashboard_spec.rb b/spec/requests/dashboard_spec.rb index 34d499c233ea3..b742c2580caf5 100644 --- a/spec/requests/dashboard_spec.rb +++ b/spec/requests/dashboard_spec.rb @@ -46,7 +46,6 @@ context "when logged in" do it "renders user's organization articles" do - organization = create(:organization) user.update(organization_id: organization.id, org_admin: true) article.update(organization_id: organization.id) login_as user diff --git a/spec/requests/events_spec.rb b/spec/requests/events_spec.rb index ae2394ae2c5c1..f316d918c92c7 100644 --- a/spec/requests/events_spec.rb +++ b/spec/requests/events_spec.rb @@ -1,9 +1,8 @@ require "rails_helper" RSpec.describe "Events", type: :request do - before do - @event = create(:event) - end + let(:event) { create(:event) } + describe "GET events" do it "returns index page" do get "/events" @@ -11,10 +10,9 @@ end it "returns event show page" do - @event.published = true - @event.save - get "/events/#{@event.slug}" - expect(response.body).to include @event.title + event.update(published: true) + get "/events/#{event.slug}" + expect(response.body).to include event.title end end -end \ No newline at end of file +end diff --git a/spec/requests/feature_toggle_spec.rb b/spec/requests/feature_toggle_spec.rb index 2ef4ac1f92edb..9a72052f82ec8 100644 --- a/spec/requests/feature_toggle_spec.rb +++ b/spec/requests/feature_toggle_spec.rb @@ -3,7 +3,7 @@ RSpec.describe "internal/features", type: :request do describe "GET /internal/features" do it "has proper headline" do - user = create(:user) + create(:user) get "/internal/features" expect(response.body).to include("Practical Developer Features") end diff --git a/spec/requests/feedback_messages_create_spec.rb b/spec/requests/feedback_messages_create_spec.rb index 1b4ca7c9e52da..fa62aaa6b5e68 100644 --- a/spec/requests/feedback_messages_create_spec.rb +++ b/spec/requests/feedback_messages_create_spec.rb @@ -2,11 +2,13 @@ RSpec.describe "feedback_messages", type: :request do describe "POST /feedback_messages" do + # rubocop:disable RSpec/AnyInstance before do allow_any_instance_of(FeedbackMessagesController). to receive(:recaptcha_verified?).and_return(true) allow_any_instance_of(Slack::Notifier).to receive(:ping).and_return(true) end + # rubocop:enable RSpec/AnyInstance valid_abuse_report_params = { feedback_message: { diff --git a/spec/requests/followed_articles_spec.rb b/spec/requests/followed_articles_spec.rb index 890e69d0587b5..b8a01bb3d14ac 100644 --- a/spec/requests/followed_articles_spec.rb +++ b/spec/requests/followed_articles_spec.rb @@ -2,17 +2,20 @@ RSpec.describe "FollowedArticles", type: :request do describe "GET followed articles index" do + let(:user) { create(:user) } + before do - @user = create(:user) - login_as @user + login_as user end + it "returns empty articles array if not following anyone" do get "/followed_articles" expect(JSON.parse(response.body)["articles"]).to eq([]) end + it "returns articles of tag I follow" do article = create(:article) - @user.follow(Tag.find_by_name(article.tag_list.first)) + user.follow(Tag.find_by_name(article.tag_list.first)) get "/followed_articles" expect(JSON.parse(response.body)["articles"].first["title"]).to eq(article.title) end diff --git a/spec/requests/follows_api_spec.rb b/spec/requests/follows_api_spec.rb index 10cb291ea5353..2db49d838207a 100644 --- a/spec/requests/follows_api_spec.rb +++ b/spec/requests/follows_api_spec.rb @@ -3,21 +3,23 @@ RSpec.describe "FollowsApi", type: :request do describe "POST /api/follows" do let(:user) { create(:user) } - let(:user_2) { create(:user) } - let(:user_3) { create(:user) } - let(:user_4) { create(:user) } - let(:user_5) { create(:user) } + let(:user2) { create(:user) } + let(:user3) { create(:user) } + let(:user4) { create(:user) } + let(:user5) { create(:user) } + let(:users_hash) do + [{ id: user2.id }, { id: user3.id }, { id: user4.id }, { id: user5.id }].to_json + end + it "returns empty if user not signed in" do - users_hash = [{id: user_2.id}, {id: user_3.id}, {id: user_4.id}, {id: user_5.id}].to_json post "/api/follows", params: { users: users_hash } expect(response.body.size).to eq(0) end it "makes successful ping" do sign_in user - users_hash = [{id: user_2.id}, {id: user_3.id}, {id: user_4.id}, {id: user_5.id}].to_json post "/api/follows", params: { users: users_hash } expect(response.body).to include("outcome") end end -end \ No newline at end of file +end diff --git a/spec/requests/image_uploads_spec.rb b/spec/requests/image_uploads_spec.rb index c2f72371d9643..ceca73854cb8e 100644 --- a/spec/requests/image_uploads_spec.rb +++ b/spec/requests/image_uploads_spec.rb @@ -4,6 +4,18 @@ describe "POST/image_uploads" do let(:user) { create(:user) } let(:headers) { { "Content-Type": "application/json", Accept: "application/json" } } + let(:image) do + Rack::Test::UploadedFile.new( + File.join(Rails.root, "spec", "support", "fixtures", "images", "image1.jpeg"), + "image/jpeg", + ) + end + let(:bad_image) do + Rack::Test::UploadedFile.new( + File.join(Rails.root, "spec", "support", "fixtures", "images", "bad-image.jpg"), + "image/jpeg", + ) + end context "when not logged-in" do it "responds with 401" do @@ -13,24 +25,23 @@ end context "when logged-in" do - it "returns json" do + before do sign_in user + end + + it "returns json" do post "/image_uploads", headers: headers expect(response.content_type).to eq("application/json") end it "provides a link" do # this test is a little flimsy - sign_in user - image = Rack::Test::UploadedFile.new(File.join(Rails.root, "spec", "support", "fixtures", "images", "image1.jpeg"), "image/jpeg") post "/image_uploads", headers: headers, params: { image: image } expect(response.body).to match("\/i\/.+\.") end it "prevents image with resolutions larger than 4096x4096" do - sign_in user - image = Rack::Test::UploadedFile.new(File.join(Rails.root, "spec", "support", "fixtures", "images", "bad-image.jpg"), "image/jpeg") - expect { post("/image_uploads", headers: headers, params: { image: image }) }. + expect { post("/image_uploads", headers: headers, params: { image: bad_image }) }. to raise_error(CarrierWave::IntegrityError) end end diff --git a/spec/requests/notification_counts_spec.rb b/spec/requests/notification_counts_spec.rb index d2972b2ccf4ef..8899b3ad3a319 100644 --- a/spec/requests/notification_counts_spec.rb +++ b/spec/requests/notification_counts_spec.rb @@ -8,4 +8,4 @@ expect(response.body).to eq("1") end end -end \ No newline at end of file +end diff --git a/spec/requests/notifications_spec.rb b/spec/requests/notifications_spec.rb index 9fbcad25a6a16..5c0db400a08f5 100644 --- a/spec/requests/notifications_spec.rb +++ b/spec/requests/notifications_spec.rb @@ -12,6 +12,7 @@ before do sign_in user end + it "renders page with proper sidebar" do get "/notifications" expect(response.body).to include("Notifications") diff --git a/spec/requests/organizations_update_spec.rb b/spec/requests/organizations_update_spec.rb index bebc1965bbef9..7f53b1db7026f 100644 --- a/spec/requests/organizations_update_spec.rb +++ b/spec/requests/organizations_update_spec.rb @@ -1,7 +1,7 @@ require "rails_helper" RSpec.describe "OrganizationsUpdate", type: :request do - let(:organization) { create(:organization)} + let(:organization) { create(:organization) } let(:user) { create(:user, organization_id: organization.id) } let(:article) { create(:article, user_id: user.id) } let(:comment) { create(:comment, user_id: user.id, commentable_id: article.id) } diff --git a/spec/requests/pages_spec.rb b/spec/requests/pages_spec.rb index 3f2a57ae1d336..3475cc7076969 100644 --- a/spec/requests/pages_spec.rb +++ b/spec/requests/pages_spec.rb @@ -65,7 +65,6 @@ end end - describe "GET /live" do let(:user) { create(:user) } @@ -123,4 +122,4 @@ end end end -end +end diff --git a/spec/requests/podcast_episodes_api_spec.rb b/spec/requests/podcast_episodes_api_spec.rb index a8fba1e5b9af4..8cc39fc482a0d 100644 --- a/spec/requests/podcast_episodes_api_spec.rb +++ b/spec/requests/podcast_episodes_api_spec.rb @@ -1,4 +1,4 @@ -require 'rails_helper' +require "rails_helper" vcr_option = { cassette_name: "se_daily_rss_feed", @@ -6,23 +6,28 @@ } RSpec.describe "ArticlesApi", type: :request, vcr: vcr_option do + let(:podcast) { create(:podcast, feed_url: "http://softwareengineeringdaily.com/feed/podcast/") } + before do - @podcast = FactoryBot.create(:podcast, feed_url: "http://softwareengineeringdaily.com/feed/podcast/") - PodcastFeed.new.get_episodes(@podcast, 2) + PodcastFeed.new.get_episodes(podcast, 2) end + describe "GET /api/articles" do it "returns json response" do get "/api/podcast_episodes" expect(response.content_type).to eq("application/json") end + it "returns podcast episodes" do get "/api/podcast_episodes" expect(JSON.parse(response.body).size).to eq(2) end + it "returns podcast episodes of specific podcast if passed username" do - get "/api/podcast_episodes?username=#{@podcast.slug}" + get "/api/podcast_episodes?username=#{podcast.slug}" expect(JSON.parse(response.body).size).to eq(2) end + it "returns nothing is passed invalid podcast slug" do expect { get "/api/podcast_episodes?username=nothing_#{rand(1000000000000000)}" }. to raise_error(ActionController::RoutingError) diff --git a/spec/requests/pusher_auth_spec.rb b/spec/requests/pusher_auth_spec.rb index ac237613a4bc5..f4db32eb8d642 100644 --- a/spec/requests/pusher_auth_spec.rb +++ b/spec/requests/pusher_auth_spec.rb @@ -3,10 +3,11 @@ RSpec.describe "PusherAuth", type: :request do let(:user) { build(:user) } let(:chat_channel) { build(:chat_channel) } + describe "POST /pusher/auth" do it "returns forbidden with invalid channel" do post "/pusher/auth", params: { - channel_name: "hey hey hey hey" + channel_name: "hey hey hey hey", } expect(response.body).to include("Forbidden") end diff --git a/spec/requests/reactions_api_spec.rb b/spec/requests/reactions_api_spec.rb index 9ed3fd3d70f3c..0a54e2507c7e4 100644 --- a/spec/requests/reactions_api_spec.rb +++ b/spec/requests/reactions_api_spec.rb @@ -2,20 +2,27 @@ require "rails_helper" RSpec.describe "ArticlesApi", type: :request do + let(:user) { create(:user) } + let(:article) { create(:article) } + before do - @user = FactoryBot.create(:user) - @user.update(secret:"TEST_SECRET") - @user.add_role(:super_admin) - @article = FactoryBot.create(:article) + user.update(secret: "TEST_SECRET") + user.add_role(:super_admin) end + describe "POST /api/reactions" do it "creates a new reactions" do - post "/api/reactions", params: {reactable_id: @article.id, reactable_type: "Article", category: "like", key: @user.secret} - expect(Reaction.last.reactable_id).to eq(@article.id) + post "/api/reactions", params: { + reactable_id: article.id, reactable_type: "Article", category: "like", key: user.secret + } + expect(Reaction.last.reactable_id).to eq(article.id) end + it "rejects non-authorized users" do - @user.remove_role(:super_admin) - post "/api/reactions", params: {reactable_id: @article.id, reactable_type: "Article", category: "like", key: @user.secret} + user.remove_role(:super_admin) + post "/api/reactions", params: { + reactable_id: article.id, reactable_type: "Article", category: "like", key: user.secret + } expect(response).to have_http_status(422) end end diff --git a/spec/requests/reactions_spec.rb b/spec/requests/reactions_spec.rb index 1b26c5bbcc260..213d24a49f4b8 100644 --- a/spec/requests/reactions_spec.rb +++ b/spec/requests/reactions_spec.rb @@ -96,7 +96,7 @@ { reactable_id: article.id, reactable_type: "Article", - category: "like" + category: "like", } end diff --git a/spec/requests/reading_list_index_spec.rb b/spec/requests/reading_list_index_spec.rb index c6ab925d2388f..0257bfac77644 100644 --- a/spec/requests/reading_list_index_spec.rb +++ b/spec/requests/reading_list_index_spec.rb @@ -5,6 +5,7 @@ user = create(:user) sign_in user end + describe "GET reading list" do it "returns reading list page" do get "/readinglist" diff --git a/spec/requests/rss_feed_spec.rb b/spec/requests/rss_feed_spec.rb index 934581b4bd1df..3a6d846d080a9 100644 --- a/spec/requests/rss_feed_spec.rb +++ b/spec/requests/rss_feed_spec.rb @@ -1,11 +1,9 @@ require "rails_helper" RSpec.describe "RssFeed", type: :request do - before do - @user = FactoryBot.create(:user) - @organization = FactoryBot.create(:organization) - @article = FactoryBot.create(:article, user_id: @user.id, featured: true) - end + let(:user) { FactoryBot.create(:user) } + let(:organization) { FactoryBot.create(:organization) } + let(:article) { FactoryBot.create(:article, user_id: user.id, featured: true) } describe "GET query page" do it "renders feed" do @@ -13,13 +11,12 @@ expect(response.body).to include("https://dev.to") end it "renders user feed" do - get "/feed/#{@user.username}" - expect(response.body).to include("https://dev.to/#{@user.username}") + get "/feed/#{user.username}" + expect(response.body).to include("https://dev.to/#{user.username}") end it "renders organization feed" do - get "/feed/#{@organization.slug}" - expect(response.body).to include("https://dev.to/#{@organization.slug}") + get "/feed/#{organization.slug}" + expect(response.body).to include("https://dev.to/#{organization.slug}") end end - -end \ No newline at end of file +end diff --git a/spec/requests/social_previews_spec.rb b/spec/requests/social_previews_spec.rb index 9d476e644e5ec..adbf3d7c25641 100644 --- a/spec/requests/social_previews_spec.rb +++ b/spec/requests/social_previews_spec.rb @@ -1,36 +1,36 @@ require "rails_helper" RSpec.describe "SocialPreviews", type: :request do - - before do - @user = create(:user) - @tag = create(:tag) - @organization = create(:organization) - @article = create(:article, user_id: @user.id) - end + let(:user) { create(:user) } + let(:tag) { create(:tag) } + let(:organization) { create(:organization) } + let(:article) { create(:article, user_id: user.id) } describe "GET /social_previews/article/:id" do it "renders proper article title" do - get "/social_previews/article/#{@article.id}" - expect(response.body).to include CGI.escapeHTML(@article.title) + get "/social_previews/article/#{article.id}" + expect(response.body).to include CGI.escapeHTML(article.title) end end + describe "GET /social_previews/user/:id" do it "renders proper user name" do - get "/social_previews/user/#{@user.id}" - expect(response.body).to include CGI.escapeHTML(@user.name) + get "/social_previews/user/#{user.id}" + expect(response.body).to include CGI.escapeHTML(user.name) end end + describe "GET /social_previews/user/:id" do it "renders proper organization name" do - get "/social_previews/organization/#{@organization.id}" - expect(response.body).to include CGI.escapeHTML(@organization.name) + get "/social_previews/organization/#{organization.id}" + expect(response.body).to include CGI.escapeHTML(organization.name) end end + describe "GET /social_previews/user/:id" do it "renders proper tag name" do - get "/social_previews/tag/#{@tag.id}" - expect(response.body).to include CGI.escapeHTML(@tag.name) + get "/social_previews/tag/#{tag.id}" + expect(response.body).to include CGI.escapeHTML(tag.name) end end end diff --git a/spec/requests/stories_index_spec.rb b/spec/requests/stories_index_spec.rb index 1c9cd6c126ed8..7555738bc34c7 100644 --- a/spec/requests/stories_index_spec.rb +++ b/spec/requests/stories_index_spec.rb @@ -7,26 +7,31 @@ expect(response.body).to include("key links") end end + describe "GET query page" do it "renders page with proper header" do get "/search?q=hello" expect(response.body).to include("query-header-text") end end + describe "GET podcast index" do it "renders page with proper header" do podcast = create(:podcast) - get "/"+podcast.slug + get "/" + podcast.slug expect(response.body).to include(podcast.title) end end + describe "GET tag index" do it "renders page with proper header" do tag = create(:tag) get "/t/#{tag.name}" expect(response.body).to include(tag.name) end - it "rendewrs page with top/week etc." do + + # rubocop:disable RSpec/ExampleLength, RSpec/MultipleExpectations + it "renders page with top/week etc." do tag = create(:tag) get "/t/#{tag.name}/top/week" expect(response.body).to include(tag.name) @@ -37,10 +42,12 @@ get "/t/#{tag.name}/top/infinity" expect(response.body).to include(tag.name) end + # rubocop:enable RSpec/ExampleLength, RSpec/MultipleExpectations + it "renders tag after alias change" do tag = create(:tag) - tag_2 = create(:tag, alias_for: tag.name) - get "/t/#{tag_2.name}" + tag2 = create(:tag, alias_for: tag.name) + get "/t/#{tag2.name}" expect(response.body).to redirect_to "/t/#{tag.name}" end end diff --git a/spec/requests/stories_show_spec.rb b/spec/requests/stories_show_spec.rb index 7ecd72ae02bf8..289780710bd05 100644 --- a/spec/requests/stories_show_spec.rb +++ b/spec/requests/stories_show_spec.rb @@ -1,66 +1,69 @@ require "rails_helper" RSpec.describe "StoriesShow", type: :request do - before do - @user = FactoryBot.create(:user) - @article = FactoryBot.create(:article, user_id: @user.id) - end + let(:user) { FactoryBot.create(:user) } + let(:article) { FactoryBot.create(:article, user_id: user.id) } describe "GET /user" do it "renders to appropriate page" do - get @article.path - expect(response.body).to include CGI.escapeHTML(@article.title) + get article.path + expect(response.body).to include CGI.escapeHTML(article.title) end + it "renders to appropriate if article belongs to org" do - @article.update(organization_id: create(:organization).id) - get @article.path - expect(response.body).to include CGI.escapeHTML(@article.title) + article.update(organization_id: create(:organization).id) + get article.path + expect(response.body).to include CGI.escapeHTML(article.title) end + it "redirects to appropriate if article belongs to org and user visits user version" do - @article.update(organization_id: create(:organization).id) - get "/#{@article.user.username}/#{@article.slug}" - expect(response.body).to redirect_to @article.path + article.update(organization_id: create(:organization).id) + get "/#{article.user.username}/#{article.slug}" + expect(response.body).to redirect_to article.path end + it "renders to appropriate page if user changes username" do - old_username = @user.username - @user.update(username: "new_hotness_#{rand(10000)}") - get "/#{old_username}/#{@article.slug}" - expect(response.body).to redirect_to("/#{@user.username}/#{@article.slug}") + old_username = user.username + user.update(username: "new_hotness_#{rand(10000)}") + get "/#{old_username}/#{article.slug}" + expect(response.body).to redirect_to("/#{user.username}/#{article.slug}") end + it "renders to appropriate page if user changes username twice" do - old_username = @user.username - @user.update(username: "new_hotness_#{rand(10000)}") - @user.update(username: "new_new_username_#{rand(10000)}") - get "/#{old_username}/#{@article.slug}" - expect(response.body).to redirect_to("/#{@user.username}/#{@article.slug}") + old_username = user.username + user.update(username: "new_hotness_#{rand(10000)}") + user.update(username: "new_new_username_#{rand(10000)}") + get "/#{old_username}/#{article.slug}" + expect(response.body).to redirect_to("/#{user.username}/#{article.slug}") end + it "renders to appropriate page if user changes username twice and go to middle username" do - old_username = @user.username - @user.update(username: "new_hotness_#{rand(10000)}") - middle_username = @user.username - @user.update(username: "new_new_username_#{rand(10000)}") - get "/#{middle_username}/#{@article.slug}" - expect(response.body).to redirect_to("/#{@user.username}/#{@article.slug}") + user.update(username: "new_hotness_#{rand(10000)}") + middle_username = user.username + user.update(username: "new_new_username_#{rand(10000)}") + get "/#{middle_username}/#{article.slug}" + expect(response.body).to redirect_to("/#{user.username}/#{article.slug}") end + it "renders second and third users if present" do - user_2 = create(:user) - user_3 = create(:user) - @article.update(second_user_id: user_2.id, third_user_id: user_3.id) - get @article.path - expect(response.body).to include "with " + user2 = create(:user) + user3 = create(:user) + article.update(second_user_id: user2.id, third_user_id: user3.id) + get article.path + expect(response.body).to include "with " end + + # rubocop:disable RSpec/ExampleLength it "renders articles of long length without breaking" do # This is a pretty weak test, just to exercise different lengths with no breakage - @article.title = (0...75).map { (65 + rand(26)).chr }.join - @article.save - get @article.path - @article.title = (0...100).map { (65 + rand(26)).chr }.join - @article.save - get @article.path - @article.title = (0...118).map { (65 + rand(26)).chr }.join - @article.save - get @article.path + article.update(title: (0...75).map { rand(65..90).chr }.join) + get article.path + article.update(title: (0...100).map { rand(65..90).chr }.join) + get article.path + article.update(title: (0...118).map { rand(65..90).chr }.join) + get article.path expect(response.body).to include "title" end + # rubocop:enable RSpec/ExampleLength end end diff --git a/spec/requests/stripe_active_cards_spec.rb b/spec/requests/stripe_active_cards_spec.rb index 880527c2937d2..5856c9ee9aafc 100644 --- a/spec/requests/stripe_active_cards_spec.rb +++ b/spec/requests/stripe_active_cards_spec.rb @@ -21,7 +21,6 @@ def valid_instance(user = user_one, amount = 1200) MembershipService.new(Stripe::Customer.retrieve(user.stripe_id_code), user, amount) end - describe "POST StripeActiveCards#create" do it "successfully adds a card to the correct user" do post "/stripe_active_cards", params: { stripe_token: stripe_helper.generate_card_token } diff --git a/spec/requests/stripe_subscriptions_spec.rb b/spec/requests/stripe_subscriptions_spec.rb index 15fd8b95d3d58..46952172ddfbc 100644 --- a/spec/requests/stripe_subscriptions_spec.rb +++ b/spec/requests/stripe_subscriptions_spec.rb @@ -1,3 +1,4 @@ +# rubocop:disable RSpec/ExampleLength, RSpec/MultipleExpectations require "rails_helper" RSpec.describe "StripeSubscriptions", type: :request do @@ -132,7 +133,6 @@ expect(user.stripe_id_code).not_to eq(nil) expect(user.has_role?(:level_1_member)).to eq(false) end - end end @@ -170,3 +170,4 @@ end end end +# rubocop:enable RSpec/ExampleLength, RSpec/MultipleExpectations diff --git a/spec/requests/tags_api_spec.rb b/spec/requests/tags_api_spec.rb index 2ac791817df7c..39eb3d856a6db 100644 --- a/spec/requests/tags_api_spec.rb +++ b/spec/requests/tags_api_spec.rb @@ -1,3 +1,4 @@ +# rubocop:disable RSpec/MultipleExpectations require "rails_helper" RSpec.describe "ArticlesApi", type: :request do @@ -21,3 +22,4 @@ end end end +# rubocop:enable RSpec/MultipleExpectations diff --git a/spec/requests/twilio_tokens_spec.rb b/spec/requests/twilio_tokens_spec.rb index 4d4b85ea32ff1..a64b70a7f4325 100644 --- a/spec/requests/twilio_tokens_spec.rb +++ b/spec/requests/twilio_tokens_spec.rb @@ -3,7 +3,7 @@ RSpec.describe "TwilioTokens", type: :request do let(:user) { create(:user) } let(:chat_channel) { create(:chat_channel) } - + before do sign_in user end diff --git a/spec/requests/users_api_spec.rb b/spec/requests/users_api_spec.rb index dd5d4ff649542..d9dc90e6b610a 100644 --- a/spec/requests/users_api_spec.rb +++ b/spec/requests/users_api_spec.rb @@ -1,11 +1,12 @@ require "rails_helper" RSpec.describe "ArticlesApi", type: :request do + let(:user) { create(:user) } + let(:tag) { create(:tag) } + describe "GET /api/users" do it "returns user objects" do - tag = create(:tag) other_user = create(:user, tag_list: tag.name) - user = create(:user) user.follow(tag) sign_in user get "/api/users?state=follow_suggestions" @@ -15,7 +16,6 @@ describe "GET /api/users/:id" do it "returns user show object" do - user = create(:user) get "/api/users/#{user.id}" expect(response.body).to include(user.name) end diff --git a/spec/requests/users_onboarding_spec.rb b/spec/requests/users_onboarding_spec.rb index 5806e72a4016d..f434df4924484 100644 --- a/spec/requests/users_onboarding_spec.rb +++ b/spec/requests/users_onboarding_spec.rb @@ -1,15 +1,16 @@ require "rails_helper" RSpec.describe "UsersOnboarding", type: :request do + let(:user) { create(:user, saw_onboarding: false) } + before do - @user = create(:user, saw_onboarding: false) - login_as @user + login_as user end describe "PATCH /onboarding_update" do it "updates saw_onboarding boolean" do patch "/onboarding_update.json", params: {} - expect(@user.saw_onboarding).to eq(true) + expect(user.saw_onboarding).to eq(true) end end end diff --git a/spec/requests/videos_spec.rb b/spec/requests/videos_spec.rb index 7a874a335c105..53f64a8760227 100644 --- a/spec/requests/videos_spec.rb +++ b/spec/requests/videos_spec.rb @@ -7,12 +7,12 @@ describe "GET /videos/new" do context "when not authorized" do it "redirects non-logged in users" do - expect { get "/videos/new"}.to raise_error(Pundit::NotAuthorizedError) + expect { get "/videos/new" }.to raise_error(Pundit::NotAuthorizedError) end it "redirects logged in users" do login_as unauthorized_user - expect { get "/videos/new"}.to raise_error(Pundit::NotAuthorizedError) + expect { get "/videos/new" }.to raise_error(Pundit::NotAuthorizedError) end end @@ -28,12 +28,12 @@ describe "POST /videos" do context "when not authorized" do it "redirects non-logged in users" do - expect { post "/videos"}.to raise_error(Pundit::NotAuthorizedError) + expect { post "/videos" }.to raise_error(Pundit::NotAuthorizedError) end it "redirects logged in users" do login_as unauthorized_user - expect { post "/videos"}.to raise_error(Pundit::NotAuthorizedError) + expect { post "/videos" }.to raise_error(Pundit::NotAuthorizedError) end end @@ -44,8 +44,8 @@ valid_params = { article: { - video: "something.mp4" - } + video: "something.mp4", + }, } xit "creates an article for the logged in user" do diff --git a/spec/routing/all_routes_spec.rb b/spec/routing/all_routes_spec.rb index eb6d91ca869b0..362dbb054b5d3 100644 --- a/spec/routing/all_routes_spec.rb +++ b/spec/routing/all_routes_spec.rb @@ -1,5 +1,4 @@ - -require 'rails_helper' +require "rails_helper" RSpec.describe "all routes", type: :routing do let(:podcast) { create(:podcast) } @@ -21,6 +20,7 @@ ) end + # rubocop:disable RSpec/ExampleLength it "renders a user's story successfully" do expect(get: "/ben/this-is-a-slug").to route_to( controller: "stories", @@ -29,8 +29,9 @@ username: "ben", ) end + # rubocop:enable RSpec/ExampleLength - context "redirected routes" do + context "when redirected routes" do include RSpec::Rails::RequestExampleGroup it "redirects /shop to shop.dev.to" do diff --git a/spec/services/membership_service_spec.rb b/spec/services/membership_service_spec.rb index 3a19fd59cc7f2..073cfba14855c 100644 --- a/spec/services/membership_service_spec.rb +++ b/spec/services/membership_service_spec.rb @@ -7,6 +7,7 @@ let(:stripe_source_token) { stripe_helper.generate_card_token } before { StripeMock.start } + after { StripeMock.stop } def valid_instance(user = user_one, amount = 1200) @@ -31,6 +32,7 @@ def valid_instance(user = user_one, amount = 1200) describe "#initialize" do context "when evoked on a user that already has subscription" do + # rubocop:disable RSpec/ExampleLength it "returns an object with subscription" do customer = Stripe::Customer.create( email: "stripe_tester@dev.to", @@ -46,9 +48,12 @@ def valid_instance(user = user_one, amount = 1200) statement_descriptor: "DEV membership", ) Stripe::Subscription.create(customer: customer.id, plan: plan.id) - test = described_class.new(Stripe::Customer.retrieve(user_one.stripe_id_code), user_one, 1200) + test = described_class.new( + Stripe::Customer.retrieve(user_one.stripe_id_code), user_one, 1200 + ) expect(test.subscription).not_to be(nil) end + # rubocop:enable RSpec/ExampleLength end end diff --git a/spec/services/suggester/articles/boosted_spec.rb b/spec/services/suggester/articles/boosted_spec.rb index 08c510081d188..34bb05f8e152d 100644 --- a/spec/services/suggester/articles/boosted_spec.rb +++ b/spec/services/suggester/articles/boosted_spec.rb @@ -1,16 +1,16 @@ -require 'rails_helper' +require "rails_helper" RSpec.describe Suggester::Articles::Boosted do let(:user) { create(:user) } let(:organization) { create(:organization) } let(:tag) { create(:tag, supported: true) } let(:article) { create(:article, tags: [tag.name], featured: true) } - let(:article_3) { create(:article, tags: [tag.name], featured: true, boosted_additional_articles: true, organization_id: organization.id) } let(:reaction) { create(:reaction, user_id: user.id, reactable_id: article.id) } it "returns an article" do user.follow(tag) - article_2 = create(:article, tags: [tag.name], featured: true, boosted_additional_articles: true, organization_id: organization.id) - expect(described_class.new(user, article, {area: "additional_articles"}).suggest.id).to eq article_2.id + article2 = create(:article, tags: [tag.name], featured: true, boosted_additional_articles: true, organization_id: organization.id) # rubocop:disable Metrics/LineLength + suggested_id = described_class.new(user, article, area: "additional_articles").suggest.id + expect(suggested_id).to eq article2.id end -end \ No newline at end of file +end diff --git a/spec/services/suggester/articles/classic_spec.rb b/spec/services/suggester/articles/classic_spec.rb index f7593e160957d..7d352979b3f3a 100644 --- a/spec/services/suggester/articles/classic_spec.rb +++ b/spec/services/suggester/articles/classic_spec.rb @@ -1,4 +1,4 @@ -require 'rails_helper' +require "rails_helper" RSpec.describe Suggester::Articles::Classic do let(:user) { create(:user) } @@ -9,8 +9,8 @@ it "returns an article" do user.follow(tag) create(:reaction, user_id: user.id, reactable_id: article.id) - create(:reaction, user_id: user.id, reactable_id: article.id, category:"thinking") - create(:reaction, user_id: user.id, reactable_id: article.id, category:"unicorn") + create(:reaction, user_id: user.id, reactable_id: article.id, category: "thinking") + create(:reaction, user_id: user.id, reactable_id: article.id, category: "unicorn") expect(described_class.new(user).get.id).to eq article.id end @@ -19,16 +19,18 @@ expect(described_class.new(user).get).to eq nil end + # rubocop:disable RSpec/ExampleLength it "returns single article if multiple qualify" do user.follow(tag) create(:reaction, user_id: user.id, reactable_id: article.id) - create(:reaction, user_id: user.id, reactable_id: article.id, category:"thinking") - create(:reaction, user_id: user.id, reactable_id: article.id, category:"unicorn") + create(:reaction, user_id: user.id, reactable_id: article.id, category: "thinking") + create(:reaction, user_id: user.id, reactable_id: article.id, category: "unicorn") user2 = create(:user) article2 = create(:article, user_id: user2.id) create(:reaction, user_id: user2.id, reactable_id: article2.id) - create(:reaction, user_id: user2.id, reactable_id: article2.id, category:"thinking") - create(:reaction, user_id: user2.id, reactable_id: article2.id, category:"unicorn") + create(:reaction, user_id: user2.id, reactable_id: article2.id, category: "thinking") + create(:reaction, user_id: user2.id, reactable_id: article2.id, category: "unicorn") expect(described_class.new(user).get.id).to eq article.id end + # rubocop:enable RSpec/ExampleLength end diff --git a/spec/services/suggester/users/recent_spec.rb b/spec/services/suggester/users/recent_spec.rb index baeb6d4124ba9..1849ce9ceb8bf 100644 --- a/spec/services/suggester/users/recent_spec.rb +++ b/spec/services/suggester/users/recent_spec.rb @@ -4,12 +4,12 @@ let(:user) { create(:user) } it "does not include calling user" do - 3.times { create(:user) } + create_list(:user, 3) expect(described_class.new(user).suggest).not_to include(user) end it "returns the same number created" do - 3.times { create(:user) } + create_list(:user, 3) expect(described_class.new(user).suggest.size).to eq(3) end end diff --git a/spec/services/suggester/users/sidebar_spec.rb b/spec/services/suggester/users/sidebar_spec.rb index b6deec3a77ece..eb4066eec0a93 100644 --- a/spec/services/suggester/users/sidebar_spec.rb +++ b/spec/services/suggester/users/sidebar_spec.rb @@ -4,14 +4,14 @@ let(:user) { create(:user) } it "does not include calling user" do - 3.times { create(:user) } + create_list(:user, 3) tags = [] 3.times { tags << create(:tag) } expect(described_class.new(user, tags).suggest).not_to include(user) end it "returns the same number created" do - 3.times { create(:user) } + create_list(:user, 3) tags = [] 3.times { tags << create(:tag) } expect(described_class.new(user, tags).suggest.size).to eq(0) diff --git a/spec/services/user_role_service_spec.rb b/spec/services/user_role_service_spec.rb index b7b913668afde..893db5f09f0d6 100644 --- a/spec/services/user_role_service_spec.rb +++ b/spec/services/user_role_service_spec.rb @@ -63,13 +63,15 @@ it "adds workshop_expiration date with valid params" do expiration_date = Time.now + 1.year - described_class.new(user).send(:new_roles?, scholar: "1", workshop_expiration: expiration_date) + described_class.new(user). + send(:new_roles?, scholar: "1", workshop_expiration: expiration_date) expect(user.workshop_expiration).to eq(expiration_date) end it "doesn't add a workshop_expiration date if scholar is not checked" do expiration_date = Time.now + 1.year - described_class.new(user).send(:new_roles?, scholar: "0", workshop_expiration: expiration_date) + described_class.new(user). + send(:new_roles?, scholar: "0", workshop_expiration: expiration_date) expect(user.workshop_expiration).to eq(nil) end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 9f7b00b4058c6..d09f024279932 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -55,8 +55,8 @@ # triggering implicit auto-inclusion in groups with matching metadata. config.shared_context_metadata_behavior = :apply_to_host_groups -# The settings below are suggested to provide a good initial experience -# with RSpec, but feel free to customize to your heart's content. + # The settings below are suggested to provide a good initial experience + # with RSpec, but feel free to customize to your heart's content. # This allows you to limit a spec run to individual examples or groups # you care about by tagging them with `:focus` metadata. When nothing @@ -65,44 +65,42 @@ # metadata: `fit`, `fdescribe` and `fcontext`, respectively. config.filter_run_when_matching :focus -=begin - # Allows RSpec to persist some state between runs in order to support - # the `--only-failures` and `--next-failure` CLI options. We recommend - # you configure your source control system to ignore this file. - config.example_status_persistence_file_path = "spec/examples.txt" - - # Limits the available syntax to the non-monkey patched syntax that is - # recommended. For more details, see: - # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ - # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ - # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode - config.disable_monkey_patching! - - # Many RSpec users commonly either run the entire suite or an individual - # file, and it's useful to allow more verbose output when running an - # individual spec file. - if config.files_to_run.one? - # Use the documentation formatter for detailed output, - # unless a formatter has already been configured - # (e.g. via a command-line flag). - config.default_formatter = "doc" - end - - # Print the 10 slowest examples and example groups at the - # end of the spec run, to help surface which specs are running - # particularly slow. - config.profile_examples = 10 - - # Run specs in random order to surface order dependencies. If you find an - # order dependency and want to debug it, you can fix the order by providing - # the seed, which is printed after each run. - # --seed 1234 - config.order = :random - - # Seed global randomization in this process using the `--seed` CLI option. - # Setting this allows you to use `--seed` to deterministically reproduce - # test failures related to randomization by passing the same `--seed` value - # as the one that triggered the failure. - Kernel.srand config.seed -=end + # # Allows RSpec to persist some state between runs in order to support + # # the `--only-failures` and `--next-failure` CLI options. We recommend + # # you configure your source control system to ignore this file. + # config.example_status_persistence_file_path = "spec/examples.txt" + # + # # Limits the available syntax to the non-monkey patched syntax that is + # # recommended. For more details, see: + # # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ + # # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ + # # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode + # config.disable_monkey_patching! + # + # # Many RSpec users commonly either run the entire suite or an individual + # # file, and it's useful to allow more verbose output when running an + # # individual spec file. + # if config.files_to_run.one? + # # Use the documentation formatter for detailed output, + # # unless a formatter has already been configured + # # (e.g. via a command-line flag). + # config.default_formatter = "doc" + # end + # + # # Print the 10 slowest examples and example groups at the + # # end of the spec run, to help surface which specs are running + # # particularly slow. + # config.profile_examples = 10 + # + # # Run specs in random order to surface order dependencies. If you find an + # # order dependency and want to debug it, you can fix the order by providing + # # the seed, which is printed after each run. + # # --seed 1234 + # config.order = :random + # + # # Seed global randomization in this process using the `--seed` CLI option. + # # Setting this allows you to use `--seed` to deterministically reproduce + # # test failures related to randomization by passing the same `--seed` value + # # as the one that triggered the failure. + # Kernel.srand config.seed end diff --git a/spec/support/database_cleaner.rb b/spec/support/database_cleaner.rb index e0dbc9aa84c78..720a470326af0 100644 --- a/spec/support/database_cleaner.rb +++ b/spec/support/database_cleaner.rb @@ -3,7 +3,7 @@ DatabaseCleaner.clean_with(:truncation) end - config.before(:each) do + config.before do DatabaseCleaner.strategy = :transaction end @@ -11,11 +11,11 @@ DatabaseCleaner.strategy = :truncation end - config.before(:each) do + config.before do DatabaseCleaner.start end - config.after(:each) do + config.after do DatabaseCleaner.clean end end diff --git a/spec/support/fake_stream.rb b/spec/support/fake_stream.rb index 92b18b722a0c4..6cf866bb84953 100644 --- a/spec/support/fake_stream.rb +++ b/spec/support/fake_stream.rb @@ -1,9 +1,9 @@ # spec/support/fake_stream.rb -require 'sinatra/base' +require "sinatra/base" class FakeStream < Sinatra::Base - get '*' do - json_response 200, 'stream_feed_1.json' + get "*" do + json_response 200, "stream_feed_1.json" end private @@ -11,6 +11,6 @@ class FakeStream < Sinatra::Base def json_response(response_code, file_name) content_type :json status response_code - File.open(File.dirname(__FILE__) + '/fixtures/' + file_name, 'rb').read + File.open(File.dirname(__FILE__) + "/fixtures/" + file_name, "rb").read end end diff --git a/spec/support/request_spec_helper.rb b/spec/support/request_spec_helper.rb index 7ba2e31d18944..f7eca6e3b36cc 100644 --- a/spec/support/request_spec_helper.rb +++ b/spec/support/request_spec_helper.rb @@ -2,8 +2,8 @@ module RequestSpecHelper include Warden::Test::Helpers def self.included(base) - base.before(:each) { Warden.test_mode! } - base.after(:each) { Warden.test_reset! } + base.before { Warden.test_mode! } + base.after { Warden.test_reset! } end def sign_in(resource) diff --git a/spec/support/shared_context.rb b/spec/support/shared_context.rb index f983bdc634005..4e9117e6de240 100644 --- a/spec/support/shared_context.rb +++ b/spec/support/shared_context.rb @@ -1,4 +1,4 @@ -RSpec.shared_context "proper status" do +RSpec.shared_context "when proper status" do before do Rails.application.env_config["action_dispatch.show_detailed_exceptions"] = false Rails.application.env_config["action_dispatch.show_exceptions"] = true @@ -11,5 +11,5 @@ end RSpec.configure do |rspec| - rspec.include_context "proper status", proper_status: true + rspec.include_context "when proper status", proper_status: true end diff --git a/spec/support/stubs.rb b/spec/support/stubs.rb index 0ebfbdb0db09b..2ac87baf0ce17 100644 --- a/spec/support/stubs.rb +++ b/spec/support/stubs.rb @@ -2,45 +2,85 @@ require "rspec/rails" RSpec.configure do |config| - config.before(:each) do + config.before do # list indexes - WebMock.stub_request(:get, /.*\.algolia(net\.com|\.net)\/1\/indexes/).to_return(:body => '{ "items": [] }') + WebMock. + stub_request(:get, /.*\.algolia(net\.com|\.net)\/1\/indexes/). + to_return(body: '{ "items": [] }') # query index - WebMock.stub_request(:get, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+/).to_return(:body => '{ "hits": [ { "objectID": 42 } ], "page": 1, "hitsPerPage": 1 }') + WebMock. + stub_request(:get, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+/). + to_return(body: '{ "hits": [ { "objectID": 42 } ], "page": 1, "hitsPerPage": 1 }') # delete index - WebMock.stub_request(:delete, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+/).to_return(:body => '{ "taskID": 42 }') + WebMock. + stub_request(:delete, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+/). + to_return(body: '{ "taskID": 42 }') # clear index - WebMock.stub_request(:post, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+\/clear/).to_return(:body => '{ "taskID": 42 }') + WebMock. + stub_request(:post, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+\/clear/). + to_return(body: '{ "taskID": 42 }') # add object - WebMock.stub_request(:post, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+/).to_return(:body => '{ "taskID": 42 }') + WebMock. + stub_request(:post, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+/). + to_return(body: '{ "taskID": 42 }') # save object - WebMock.stub_request(:put, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+\/[^\/]+/).to_return(:body => '{ "taskID": 42 }') + WebMock. + stub_request(:put, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+\/[^\/]+/). + to_return(body: '{ "taskID": 42 }') # partial update - WebMock.stub_request(:put, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+\/[^\/]+\/partial/).to_return(:body => '{ "taskID": 42 }') + WebMock. + stub_request(:put, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+\/[^\/]+\/partial/). + to_return(body: '{ "taskID": 42 }') # get object - WebMock.stub_request(:get, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+\/[^\/]+/).to_return(:body => '{}') + WebMock. + stub_request(:get, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+\/[^\/]+/). + to_return(body: "{}") # delete object - WebMock.stub_request(:delete, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+\/[^\/]+/).to_return(:body => '{ "taskID": 42 }') + WebMock. + stub_request(:delete, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+\/[^\/]+/). + to_return(body: '{ "taskID": 42 }') # batch - WebMock.stub_request(:post, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+\/batch/).to_return(:body => '{ "taskID": 42 }') + WebMock. + stub_request(:post, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+\/batch/). + to_return(body: '{ "taskID": 42 }') # settings - WebMock.stub_request(:get, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+\/settings/).to_return(:body => '{}') - WebMock.stub_request(:put, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+\/settings/).to_return(:body => '{ "taskID": 42 }') + WebMock. + stub_request(:get, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+\/settings/). + to_return(body: "{}") + WebMock. + stub_request(:put, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+\/settings/). + to_return(body: '{ "taskID": 42 }') # browse - WebMock.stub_request(:get, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+\/browse/).to_return(:body => '{}') + WebMock. + stub_request(:get, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+\/browse/). + to_return(body: "{}") # operations - WebMock.stub_request(:post, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+\/operation/).to_return(:body => '{ "taskID": 42 }') + WebMock. + stub_request(:post, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+\/operation/). + to_return(body: '{ "taskID": 42 }') # tasks - WebMock.stub_request(:get, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+\/task\/[^\/]+/).to_return(:body => '{ "status": "published" }') + WebMock. + stub_request(:get, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+\/task\/[^\/]+/). + to_return(body: '{ "status": "published" }') # index keys - WebMock.stub_request(:post, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+\/keys/).to_return(:body => '{ }') - WebMock.stub_request(:get, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+\/keys/).to_return(:body => '{ "keys": [] }') + WebMock. + stub_request(:post, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+\/keys/). + to_return(body: "{ }") + WebMock. + stub_request(:get, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+\/keys/). + to_return(body: '{ "keys": [] }') # global keys - WebMock.stub_request(:post, /.*\.algolia(net\.com|\.net)\/1\/keys/).to_return(:body => '{ }') - WebMock.stub_request(:get, /.*\.algolia(net\.com|\.net)\/1\/keys/).to_return(:body => '{ "keys": [] }') - WebMock.stub_request(:get, /.*\.algolia(net\.com|\.net)\/1\/keys\/[^\/]+/).to_return(:body => '{ }') - WebMock.stub_request(:delete, /.*\.algolia(net\.com|\.net)\/1\/keys\/[^\/]+/).to_return(:body => '{ }') + WebMock. + stub_request(:post, /.*\.algolia(net\.com|\.net)\/1\/keys/).to_return(body: "{ }") + WebMock. + stub_request(:get, /.*\.algolia(net\.com|\.net)\/1\/keys/).to_return(body: '{ "keys": [] }') + WebMock. + stub_request(:get, /.*\.algolia(net\.com|\.net)\/1\/keys\/[^\/]+/).to_return(body: "{ }") + WebMock. + stub_request(:delete, /.*\.algolia(net\.com|\.net)\/1\/keys\/[^\/]+/).to_return(body: "{ }") # query POST - WebMock.stub_request(:post, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+\/query/).to_return(:body => '{ "hits": [ { "objectID": 42 } ], "page": 1, "hitsPerPage": 1 }') + WebMock. + stub_request(:post, /.*\.algolia(net\.com|\.net)\/1\/indexes\/[^\/]+\/query/). + to_return(body: '{ "hits": [ { "objectID": 42 } ], "page": 1, "hitsPerPage": 1 }') end end diff --git a/spec/views/articles_spec.rb b/spec/views/articles_spec.rb index f663fe399e9ee..f4ac7581bd735 100644 --- a/spec/views/articles_spec.rb +++ b/spec/views/articles_spec.rb @@ -1,3 +1,4 @@ +# rubocop:disable RSpec/MultipleExpectations require "rails_helper" describe "articles/show", type: :view do @@ -15,10 +16,13 @@ end def create_comment(parent_id = nil) - create(:comment, user_id: user1.id, - parent_id: parent_id ? parent_id : nil, - commentable_id: article1.id, - commentable_type: "Article") + create( + :comment, + user_id: user1.id, + parent_id: parent_id || nil, + commentable_id: article1.id, + commentable_type: "Article", + ) end it "shows user title of the article" do @@ -45,6 +49,7 @@ def create_comment(parent_id = nil) expect(rendered).to have_css("input#submit-button") end + # rubocop:disable RSpec/ExampleLength it "shows user comments of the article" do without_partial_double_verification do allow(view).to receive(:comment_class) { |a, b| helper.comment_class(a, b) } @@ -56,6 +61,7 @@ def create_comment(parent_id = nil) expect(rendered).to have_text(comment1.body_html) expect(rendered).to have_text(comment2.body_html) end + # rubocop:enable RSpec/ExampleLength end # note fully implemented yet @@ -69,3 +75,4 @@ def create_comment(parent_id = nil) # end # # end +# rubocop:enable RSpec/MultipleExpectations