discord_spec.rb 2.2 KB
Newer Older
blackst0ne's avatar
blackst0ne committed
1 2
# frozen_string_literal: true

blackst0ne's avatar
blackst0ne committed
3 4
require "spec_helper"

5 6
RSpec.describe Integrations::Discord do
  it_behaves_like "chat integration", "Discord notifications" do
blackst0ne's avatar
blackst0ne committed
7 8
    let(:client) { Discordrb::Webhooks::Client }
    let(:client_arguments) { { url: webhook_url } }
9 10 11 12 13 14 15 16 17 18
    let(:payload) do
      {
        embeds: [
          include(
            author: include(name: be_present),
            description: be_present
          )
        ]
      }
    end
blackst0ne's avatar
blackst0ne committed
19
  end
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42

  describe '#execute' do
    include StubRequests

    let(:user) { create(:user) }
    let(:project) { create(:project, :repository) }
    let(:webhook_url) { "https://example.gitlab.com/" }

    let(:sample_data) do
      Gitlab::DataBuilder::Push.build_sample(project, user)
    end

    before do
      allow(subject).to receive_messages(
        project: project,
        project_id: project.id,
        service_hook: true,
        webhook: webhook_url
      )

      WebMock.stub_request(:post, webhook_url)
    end

43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
    it 'uses the right embed parameters' do
      builder = Discordrb::Webhooks::Builder.new

      allow_next_instance_of(Discordrb::Webhooks::Client) do |client|
        allow(client).to receive(:execute).and_yield(builder)
      end

      subject.execute(sample_data)

      expect(builder.to_json_hash[:embeds].first).to include(
        description: start_with("#{user.name} pushed to branch [master](http://localhost/#{project.namespace.path}/#{project.path}/commits/master) of"),
        author: hash_including(
          icon_url: start_with('https://www.gravatar.com/avatar/'),
          name: user.name
        )
      )
    end

61 62 63 64 65 66 67 68 69
    context 'DNS rebind to local address' do
      before do
        stub_dns(webhook_url, ip_address: '192.168.2.120')
      end

      it 'does not allow DNS rebinding' do
        expect { subject.execute(sample_data) }.to raise_error(ArgumentError, /is blocked/)
      end
    end
70 71 72 73 74 75 76 77 78 79 80

    context 'when the Discord request fails' do
      before do
        WebMock.stub_request(:post, webhook_url).to_return(status: 400)
      end

      it 'logs an error and returns false' do
        expect(subject).to receive(:log_error).with('400 Bad Request')
        expect(subject.execute(sample_data)).to be(false)
      end
    end
81
  end
blackst0ne's avatar
blackst0ne committed
82
end