Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion lib/aws/sns/configurator/topic.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
66 changes: 63 additions & 3 deletions spec/aws/sns/configurator/topic_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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