Skip to content

Commit

Permalink
Merge pull request #25 from dsalahutdinov/feature/stub_logux_instead_…
Browse files Browse the repository at this point in the history
…of_webmocking

feature: faking logux requests without webmock
  • Loading branch information
dsalahutdinov committed Oct 24, 2018
2 parents f3aa3c2 + 180a54c commit 3858b3b
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 26 deletions.
26 changes: 26 additions & 0 deletions lib/logux/test.rb
Expand Up @@ -2,7 +2,33 @@

module Logux
module Test
class << self
attr_accessor :http_requests_enabled

def enable_http_requests!
raise ArgumentError unless block_given?

begin
self.http_requests_enabled = true
yield
ensure
self.http_requests_enabled = false
end
end
end

module Client
def post(params)
if Logux::Test.http_requests_enabled
super(params)
else
Logux::Test::Store.instance.add(params.to_json)
end
end
end

autoload :Helpers, 'logux/test/helpers'
autoload :Store, 'logux/test/store'
end
end
Logux::Client.prepend Logux::Test::Client
12 changes: 3 additions & 9 deletions lib/logux/test/helpers.rb
Expand Up @@ -5,21 +5,14 @@ module Test
module Helpers
extend ActiveSupport::Concern

WebMock.after_request do |request, response|
(request.uri.origin =~ /#{Logux.configuration.logux_host}/) || next
Logux::Test::Store.instance.add_request(request: request,
response: response)
end

included do
before do
stub_request(:post, Logux.configuration.logux_host)
Logux::Test::Store.instance.reset!
end
end

def logux_store
Logux::Test::Store.instance.requests
Logux::Test::Store.instance.data
end

RSpec::Matchers.define :send_to_logux do |expected|
Expand All @@ -28,7 +21,8 @@ def logux_store
actual.call
after_state = logux_store
@difference = (after_state - before_state)
.map { |dif| dif[:body].deep_symbolize_keys }
.map { |d| JSON.parse(d) }
.map(&:deep_symbolize_keys)
@difference.find do |state|
state.merge(expected || {}).deep_symbolize_keys == state
end
Expand Down
19 changes: 5 additions & 14 deletions lib/logux/test/store.rb
Expand Up @@ -5,25 +5,16 @@ module Test
class Store
include Singleton

def add_request(action)
parsed_body = parse_body(action[:request]&.body)
requests << action.merge(body: parsed_body)
def add(params)
data << params
end

def requests
@requests ||= []
def data
@data ||= []
end

def reset!
@requests = []
end

private

def parse_body(body)
JSON.parse(body)
rescue JSON::ParserError, TypeError
{}
@data = []
end
end
end
Expand Down
6 changes: 3 additions & 3 deletions spec/logux_spec.rb
Expand Up @@ -6,12 +6,12 @@
end

describe '.add' do
before { described_class.add(type) }

let(:type) { [] }

it 'makes request' do
expect(WebMock).to have_requested(:post, Logux.configuration.logux_host)
stub = stub_request(:post, Logux.configuration.logux_host)
Logux::Test.enable_http_requests! { described_class.add(type) }
expect(stub).to have_been_requested
end
end

Expand Down

0 comments on commit 3858b3b

Please sign in to comment.