diff --git a/lib/aws/sns/configurator/topic.rb b/lib/aws/sns/configurator/topic.rb index f6e2cd5..ab5bff5 100644 --- a/lib/aws/sns/configurator/topic.rb +++ b/lib/aws/sns/configurator/topic.rb @@ -48,7 +48,7 @@ def subscribe!(protocol, endpoint, options) end def publish!(message) - default_client.aws.publish(topic_arn: @arn, message: message.to_json) + default_client.aws.publish(topic_arn: @arn, message: format_message(message)) end private @@ -91,6 +91,10 @@ def build_name_formatted! def build_arn! @arn = ['arn:aws:sns', @region, account_id, @name_formatted].compact.join(':') end + + def format_message(message) + message.is_a?(Hash) ? message.to_json : message + end end end end diff --git a/spec/aws/sns/configurator/topic_spec.rb b/spec/aws/sns/configurator/topic_spec.rb index b2ba8d9..691d6fa 100644 --- a/spec/aws/sns/configurator/topic_spec.rb +++ b/spec/aws/sns/configurator/topic_spec.rb @@ -155,10 +155,70 @@ describe '#publish!' do let(:topic) { build :topic } - subject { topic.publish!(name: 'linqueta', blog: 'linqueta.com') } + let(:aws_client) { double('AwsClient') } - it 'should publish in the topic', :vcr do - is_expected.to be_truthy + before do + allow(topic).to receive_message_chain(:default_client, :aws).and_return(aws_client) + allow(aws_client).to receive(:publish) + end + + context 'when payload is a hash' do + let(:message) { { nome: 'petlove', site: 'petlove.com.br' } } + + it 'should publish in the topic with message as json' do + expect(aws_client).to receive(:publish).with( + topic_arn: topic.arn, + message: message.to_json + ) + topic.publish!(message) + end + end + + context 'when message is a json string' do + let(:json_message) { '{"nome":"petlove", "site":"petlove.com.br"}' } + + it 'should publish in the topic with message as json' do + expect(aws_client).to receive(:publish).with( + topic_arn: topic.arn, + message: json_message + ) + topic.publish!(json_message) + end + end + end + + describe '#format_message' do + let(:topic) { build :topic } + + context 'when message is a hash' do + let(:message) { { nome: 'petlove', site: 'petlove.com.br' } } + + it 'returns a valid JSON string' do + result = topic.send(:format_message, message) + + expect(result).to be_a(String) + + parsed_message = JSON.parse(result) + + expect(parsed_message['nome']).to eq('petlove') + expect(parsed_message['site']).to eq('petlove.com.br') + end + end + + context 'when the message is already a JSON string' do + let(:json_message) { '{"nome":"petlove", "site":"petlove.com.br"}' } + + it 'returns the original JSON string unchanged' do + result = topic.send(:format_message, json_message) + + expect(result).to be_a(String) + expect(result).to eq(json_message) + + parsed_message = JSON.parse(result) + + expect(parsed_message['nome']).to eq('petlove') + expect(parsed_message['site']).to eq('petlove.com.br') + end end end end