From 3dca35ba9a1522b1b09aae0753a5bbc0fc2e2faa Mon Sep 17 00:00:00 2001 From: Max Melentiev Date: Tue, 25 Jul 2017 10:58:18 +0300 Subject: [PATCH] callback_query context for RSpec --- README.md | 7 ++++++ lib/telegram/bot/rspec/integration.rb | 36 ++++++++++++++++++++++++++- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 5e95fed..ac32553 100644 --- a/README.md +++ b/README.md @@ -377,6 +377,13 @@ RSpec.describe TelegramWebhooksController, :telegram_bot do subject { -> { dispatch_command :start } } it { should respond_with_message 'Hi there!' } end + + # There is context for callback queries with related matchers. + describe '#hey_callback_query', :callback_query do + let(:data) { "hey:#{name}" } + let(:name) { 'Joe' } + it { should answer_callback_query('Hey Joe') } + it { should edit_current_message :text, text: 'Done' } end # For controller specs use diff --git a/lib/telegram/bot/rspec/integration.rb b/lib/telegram/bot/rspec/integration.rb index 84d1a24..ab2e840 100644 --- a/lib/telegram/bot/rspec/integration.rb +++ b/lib/telegram/bot/rspec/integration.rb @@ -36,14 +36,48 @@ RSpec.shared_context 'telegram/bot/integration' do end # Matcher to check response. Make sure to define `let(:chat_id)`. - def respond_with_message(expected) + def respond_with_message(expected = Regexp.new('')) raise 'Define chat_id to use respond_with_message' unless defined?(chat_id) send_telegram_message(bot, expected, chat_id: chat_id) end end +RSpec.shared_context 'telegram/bot/callback_query', callback_query: true do + include_context 'telegram/bot/integration' + + subject { -> { dispatch callback_query: payload } } + let(:payload) { {id: 11, from: from, message: message, data: data} } + let(:message) { {message_id: 22, chat: chat, text: 'message text'} } + + # Matcher to check that origin message got edited. + def edit_current_message(type, options = {}) + description = 'edit current message' + options = options.merge( + message_id: message[:message_id], + chat_id: chat_id, + ) + Telegram::Bot::RSpec::ClientMatchers::MakeTelegramRequest.new( + bot, :"editMessage#{type.to_s.camelize}", description: description + ).with(hash_including(options)) + end + + # Matcher to check that callback query is answered. + def answer_callback_query(text = Regexp.new(''), options = {}) + description = "answer callback query with #{text.inspect}" + text = a_string_matching(text) if text.is_a?(Regexp) + options = options.merge( + callback_query_id: payload[:id], + text: text, + ) + Telegram::Bot::RSpec::ClientMatchers::MakeTelegramRequest.new( + bot, :answerCallbackQuery, description: description + ).with(hash_including(options)) + end +end + RSpec.configure do |config| if config.respond_to?(:include_context) config.include_context 'telegram/bot/integration', :telegram_bot + config.include_context 'telegram/bot/callback_query', :telegram_bot, :callback_query end end