Невозможно заблокировать внешний запрос - Неверное регулярное выражение? - PullRequest
0 голосов
/ 25 июня 2018

Я пытаюсь создать stub_request, который соответствует всем запросам fcm.googleapis.com . Наш бэкэнд должен отправлять push-уведомления своим пользователям при создании новых сообщений или комментариев. Наши тесты вызывают много запросов к fcm.googleapis.com, поэтому мне нужен универсальный сопоставитель.

РЕДАКТИРОВАТЬ: Тест не удался, потому что я добавил stub_request в spec_helper. Неудачный тест был не rspec, а обычным ActionController::TestCase тестом. Виноват! : - |

спецификация / spec_helper.rb

 18 RSpec.configure do |config|
 19   require_relative "../test/mock_helper"
 20   require "webmock/rspec"
 21
 22   WebMock.disable_net_connect!
 23   config.before(:each) do
 24     stub_request(:post, "https://fcm.googleapis.com/fcm/send").
 25         with(body: /.*/).
 26         to_return(status: 200)
 27

Но когда я запускаю тесты, похоже, что WebMock не заботится о моем stub_request. Что может быть не так?

Выполнение тестов

    Error:
    PostsControllerTest#test_should_create_post:
    WebMock::NetConnectNotAllowedError: Real HTTP connections are disabled. 
Unregistered request: POST https://fcm.googleapis.com/fcm/send with body 
'{"registration_ids":[null],"notification":
{"title":"Fred Flintstone har skrevet en melding i Bedrock Sportsballteam",
"text":"New post!?"},"data":{"notification":{"avatar":null,"group_id":131900578,
"issued_at":"2018-06-25T13:37:28.746+02:00",
"full_name":"Fred Flintstone","id":700,"post_id":980190963,
"role_id":1}}}' with headers {'Authorization'=>'key=KEY', 'Content-Type'=>'application/json'}

    You can stub this request with the following snippet:

    stub_request(:post, "https://fcm.googleapis.com/fcm/send").
      with(:body => "{\"registration_ids\":[null],\"notification\":
{\"title\":\"Fred Flintstone har skrevet en melding i Bedrock Sportsballteam\",
\"text\":\"New post!?\"},\"data\":{\"notification\":
{\"avatar\":null,\"group_id\":131900578,
\"issued_at\":\"2018-06-25T13:37:28.746+02:00\",
\"full_name\":\"Fred Flintstone\",\"id\":700,\"post_id\":980190963,\"role_id\":1}}}",
           :headers => {'Authorization'=>'key=KEY', 
           'Content-Type'=>'application/json'}).
      to_return(:status => 200, :body => "", :headers => {})

Мой бэкэнд должен отправлять push-уведомление нашим пользователям, когда создается новое обновленное сообщение.

приложение / модели / post.rb

 16 class Post < ApplicationRecord
 25   after_save :send_notifications

 82   def send_notifications
 83     PUSH_NOTIFICATIONS.new_post_in_group(post: self)
 84   end

Тест бина / рельсов / контроллеры / posts_controller_test.rb: 57

 57   test "should create post" do
 58     assert_difference("Post.count") do
 59       assert_difference("PostImage.count", 3) do
 60         post :create, params: {
 61           group_id: groups(:sportsball).id,
 62           post: {
 63             text: "New post!?",
 64             is_pinned: "true"
 73           }
 74         }
 75
 76         post = Post.last
 77         assert_equal true, post.is_pinned
 78
 79         assert_response :created, response.body
 80         assert valid_json?(response.body), "Invalid json: #{response.body}"
 81
 82         json = JSON.parse(response.body).deep_symbolize_keys
 83         
 84       end
 85     end
 86   end

PushNotifications

class PushNotifications
  def initialize
    @fcm = FCM.new(ENV["FCM_SERVER_KEY"])
  end

  def new_post_in_group(post:)
    registration_ids = all_users_except_author(post)
    author           = post.user
    group            = post.group
    return unless registration_ids

    options = {
      notification: {
        title: "#{author.name} har skrevet en melding i #{group.name}",
        text: post.text.truncate(27)
      },
      data: {
        notification:
        {
          avatar: author.avatar,
          # comment_id: '646',
          group_id: group.id,
          issued_at: Time.now,
          full_name: author.name,
          id: 700, # 700 = new post. The client knows what to do by looking at this id.
          post_id: post.id,
          role_id: author.role_id(group)
        }
      }
    }
    response = @fcm.send(registration_ids, options)
    puts "Sendt: #{response}" if ENV["DEBUG"]
  end

  private

  def all_users_except_author(post)
    recipients = post.group.users.pluck(:fcm_token)
    recipients.delete(post.user.id)
    recipients
  end
end

конфиг / Инициализаторы / PushNotifications.rb

  1 require "#{Rails.root}/lib/push_notifications"
  2
  3 puts "initialize PushNotifications"
  4 PUSH_NOTIFICATIONS ||= PushNotifications.new

1 Ответ

0 голосов
/ 26 июня 2018

Тест не пройден, потому что я добавил stub_request в spec_helper.Неудачный тест был не rspec, а обычным тестом ActionController :: TestCase.Виноват!: - |

...