capybara_mock 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 57a394dbe97d73967375b025383b3ae4ff760b10316793253f9b66541cd92155
4
+ data.tar.gz: 210ef8e8b3fecbf6c4c087802ec27c2e019bc55a55bca70c47f2e2b89e1a94ef
5
+ SHA512:
6
+ metadata.gz: dcc2e3dc6243cb540d6441003339d811f65a6ba1387da2dd24511d79820f0eeb5545d2cd43618aabe0d480b4ca8ad078f69aedc39452293fac7caa47ba196256
7
+ data.tar.gz: aa2aaec43d65bf581dc3971fcca1301c31c63a4a81bad6226c9043c09e1c8354581632f479af9472ae927bb04da281b60b026e357b93e83343fbde06df1c6de4
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,33 @@
1
+ require:
2
+ - rubocop-rake
3
+ - rubocop-rspec
4
+
5
+ AllCops:
6
+ TargetRubyVersion: 2.7
7
+ NewCops: enable
8
+
9
+ Layout/LineLength:
10
+ Max: 120
11
+
12
+ Metrics/MethodLength:
13
+ Max: 20
14
+
15
+ Style/StringLiterals:
16
+ Enabled: true
17
+ EnforcedStyle: single_quotes
18
+
19
+ Style/StringLiteralsInInterpolation:
20
+ Enabled: true
21
+ EnforcedStyle: double_quotes
22
+
23
+ RSpec/ExampleLength:
24
+ Max: 50
25
+
26
+ RSpec/MultipleExpectations:
27
+ Max: 10
28
+
29
+ RSpec/NestedGroups:
30
+ Max: 4
31
+
32
+ RSpec/Rails/InferredSpecType:
33
+ Enabled: false
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2022-12-09
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at contact@railsware.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ gemspec
6
+
7
+ gem 'rack', '2.2.4'
8
+
9
+ gem 'capybara', '>= 3.35.0'
10
+ gem 'cuprite', '>= 0.14.0'
11
+
12
+ gem 'rake', '~> 13.0'
13
+
14
+ gem 'rspec', '~> 3.0'
15
+
16
+ gem 'rubocop', '~> 1.21'
17
+ gem 'rubocop-rake', '~> 0.6', require: false
18
+ gem 'rubocop-rspec', '~> 2.15', require: false
data/Gemfile.lock ADDED
@@ -0,0 +1,110 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ capybara_mock (0.1.0)
5
+ rack (>= 2.2.0)
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ addressable (2.8.1)
11
+ public_suffix (>= 2.0.2, < 6.0)
12
+ ast (2.4.2)
13
+ capybara (3.38.0)
14
+ addressable
15
+ matrix
16
+ mini_mime (>= 0.1.3)
17
+ nokogiri (~> 1.8)
18
+ rack (>= 1.6.0)
19
+ rack-test (>= 0.6.3)
20
+ regexp_parser (>= 1.5, < 3.0)
21
+ xpath (~> 3.2)
22
+ concurrent-ruby (1.1.10)
23
+ cuprite (0.14.3)
24
+ capybara (~> 3.0)
25
+ ferrum (~> 0.13.0)
26
+ diff-lcs (1.5.0)
27
+ ferrum (0.13)
28
+ addressable (~> 2.5)
29
+ concurrent-ruby (~> 1.1)
30
+ webrick (~> 1.7)
31
+ websocket-driver (>= 0.6, < 0.8)
32
+ json (2.6.3)
33
+ matrix (0.4.2)
34
+ mini_mime (1.1.2)
35
+ mini_portile2 (2.8.0)
36
+ nokogiri (1.13.10)
37
+ mini_portile2 (~> 2.8.0)
38
+ racc (~> 1.4)
39
+ nokogiri (1.13.10-arm64-darwin)
40
+ racc (~> 1.4)
41
+ nokogiri (1.13.10-x86_64-linux)
42
+ racc (~> 1.4)
43
+ parallel (1.22.1)
44
+ parser (3.1.3.0)
45
+ ast (~> 2.4.1)
46
+ public_suffix (5.0.1)
47
+ racc (1.6.1)
48
+ rack (2.2.4)
49
+ rack-test (2.0.2)
50
+ rack (>= 1.3)
51
+ rainbow (3.1.1)
52
+ rake (13.0.6)
53
+ regexp_parser (2.6.1)
54
+ rexml (3.2.5)
55
+ rspec (3.12.0)
56
+ rspec-core (~> 3.12.0)
57
+ rspec-expectations (~> 3.12.0)
58
+ rspec-mocks (~> 3.12.0)
59
+ rspec-core (3.12.0)
60
+ rspec-support (~> 3.12.0)
61
+ rspec-expectations (3.12.0)
62
+ diff-lcs (>= 1.2.0, < 2.0)
63
+ rspec-support (~> 3.12.0)
64
+ rspec-mocks (3.12.0)
65
+ diff-lcs (>= 1.2.0, < 2.0)
66
+ rspec-support (~> 3.12.0)
67
+ rspec-support (3.12.0)
68
+ rubocop (1.40.0)
69
+ json (~> 2.3)
70
+ parallel (~> 1.10)
71
+ parser (>= 3.1.2.1)
72
+ rainbow (>= 2.2.2, < 4.0)
73
+ regexp_parser (>= 1.8, < 3.0)
74
+ rexml (>= 3.2.5, < 4.0)
75
+ rubocop-ast (>= 1.23.0, < 2.0)
76
+ ruby-progressbar (~> 1.7)
77
+ unicode-display_width (>= 1.4.0, < 3.0)
78
+ rubocop-ast (1.24.0)
79
+ parser (>= 3.1.1.0)
80
+ rubocop-rake (0.6.0)
81
+ rubocop (~> 1.0)
82
+ rubocop-rspec (2.15.0)
83
+ rubocop (~> 1.33)
84
+ ruby-progressbar (1.11.0)
85
+ unicode-display_width (2.3.0)
86
+ webrick (1.7.0)
87
+ websocket-driver (0.7.5)
88
+ websocket-extensions (>= 0.1.0)
89
+ websocket-extensions (0.1.5)
90
+ xpath (3.2.0)
91
+ nokogiri (~> 1.8)
92
+
93
+ PLATFORMS
94
+ arm64-darwin-21
95
+ ruby
96
+ x86_64-linux
97
+
98
+ DEPENDENCIES
99
+ capybara (>= 3.35.0)
100
+ capybara_mock!
101
+ cuprite (>= 0.14.0)
102
+ rack (= 2.2.4)
103
+ rake (~> 13.0)
104
+ rspec (~> 3.0)
105
+ rubocop (~> 1.21)
106
+ rubocop-rake (~> 0.6)
107
+ rubocop-rspec (~> 2.15)
108
+
109
+ BUNDLED WITH
110
+ 2.3.26
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Railsware Products Studio LLC.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,179 @@
1
+ [![test](https://github.com/railsware/capybara_mock/actions/workflows/main.yml/badge.svg)](https://github.com/railsware/capybara_mock/actions/workflows/main.yml)
2
+
3
+ # CapybaraMock
4
+
5
+ Library for stubbing HTTP requests in Capybara browser.
6
+
7
+ ## Features
8
+
9
+ * Stubbing interface similar to [WebMock](https://github.com/bblimke/webmock)
10
+ * Matching requests based on
11
+ * method
12
+ * url
13
+ * query
14
+ * headers
15
+ * body
16
+
17
+ ## Supported capybara drivers
18
+
19
+ * [Cuprite](https://github.com/rubycdp/cuprite)
20
+
21
+ ## Installation
22
+
23
+ Install the gem and add to the application's Gemfile by executing:
24
+
25
+ $ bundle add capybara_mock
26
+
27
+ If bundler is not being used to manage dependencies, install the gem by executing:
28
+
29
+ $ gem install capybara_mock
30
+
31
+ ### RSpec
32
+
33
+ Add the following code to `spec/spec_helper`:
34
+
35
+ ```ruby
36
+ require 'capybara_mock/rspec'
37
+ ```
38
+
39
+ Then ensure your capybara use `:cuprite` driver for feature specs that you want to mock browser requests.
40
+
41
+ ## Usage
42
+
43
+ * `Capybara.stub_request` - stub external request by full url or regexp.
44
+ * `Capybara.stub_path` - stub internal request (to your capybara application) by path.
45
+ * `Capybara.remove_stub` - remove previously added stub to current capybara session
46
+ * `Capybara.clear_stubs` - remove all stubs for current capybara session
47
+ * `Capybara.save_unstubbed_requests` - save unstubbed browser requests from current capybara session. Useful for debugging.
48
+
49
+ ## Examples
50
+
51
+ ### Stub external request
52
+
53
+ ```ruby
54
+ CapybaraMock.stub_request(
55
+ :get, 'https://api.stripe.com/v1/balance'
56
+ ).to_return(
57
+ status: 200,
58
+ headers: {'Content-Type' => 'application/json'},
59
+ body: {amount: 10100}.to_json
60
+ )
61
+ ```
62
+
63
+ ### Stub internal request
64
+
65
+ ```ruby
66
+ CapybaraMock.stub_path(
67
+ :get, '/api/users/me'
68
+ ).to_return(
69
+ status: 200,
70
+ headers: {'Content-Type' => 'application/json'},
71
+ body: {name: 'John Doe'}.to_json
72
+ )
73
+ ```
74
+
75
+ ### Stub with specific query
76
+
77
+ ```ruby
78
+ CapybaraMock.stub_path(
79
+ :get, '/api/users'
80
+ ).with(
81
+ query: {page: 1}
82
+ ).to_return(
83
+ status: 200,
84
+ headers: {'Content-Type' => 'application/json'},
85
+ body: [].to_json
86
+ )
87
+ ```
88
+
89
+ ### Stub with specific header
90
+
91
+ ```ruby
92
+ CapybaraMock.stub_path(
93
+ :get, '/api/users/1'
94
+ ).with(
95
+ headers: {
96
+ 'Authorization' => 'Bearer ACCESS_TOKEN'
97
+ }
98
+ ).to_return(
99
+ status: 200,
100
+ headers: {'Content-Type' => 'application/json'},
101
+ body: {id: 1}.to_json
102
+ )
103
+ ```
104
+
105
+ ### Stub with specific body
106
+
107
+ ```ruby
108
+ CapybaraMock.stub_path(
109
+ :post, '/api/users'
110
+ ).with(
111
+ headers: {'Content-Type': 'application/x-www-form-urlencoded'},
112
+ body: 'first_name=John&last_name=Doe'
113
+ ).to_return(
114
+ status: 200,
115
+ headers: {'Content-Type' => 'application/json'},
116
+ body: {id: 1}.to_json
117
+ )
118
+ ```
119
+
120
+ ```ruby
121
+ CapybaraMock.stub_path(
122
+ :post, '/api/users'
123
+ ).with(
124
+ headers: {'Content-Type': 'application/json'},
125
+ body: '{"first_name":"John","last_name":"Doe"}'
126
+ ).to_return(
127
+ status: 200,
128
+ headers: {'Content-Type' => 'application/json'},
129
+ body: {id: 1}.to_json
130
+ )
131
+ ```
132
+
133
+ ## Limitation
134
+
135
+ Unfortunately Chrome DevTools Protocol still does not support all valid http response codes.
136
+ Right now it [supports](https://github.com/chromium/chromium/blob/main/net/http/http_status_code_list.h) only:
137
+ * 100, 101, 103
138
+ * 200..206
139
+ * 300..305, 307..308
140
+ * 400..418, 425, 229
141
+ * 500..505
142
+
143
+ For unsupported codes cuprite interceptor will send basic code and real code in special response header `X-Mock-Response-Status`. So you you have to add interceptor for your http client.
144
+
145
+
146
+ ### AXIOS interceptor
147
+
148
+ ```js
149
+ axios.interceptors.response.use(
150
+ (response) => response,
151
+ (error) => {
152
+ if (error.response && error.response.headers['x-mock-response-status']) {
153
+ const status = parseInt(error.response.headers['x-mock-response-status'])
154
+ error.message = `Request failed with status code ${status}`
155
+ error.response.status = status
156
+ }
157
+
158
+ return Promise.reject(error)
159
+ }
160
+ ```
161
+
162
+
163
+ ## Development
164
+
165
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
166
+
167
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
168
+
169
+ ## Contributing
170
+
171
+ Bug reports and pull requests are welcome on GitHub at https://github.com/railsware/capybara_mock. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/railsware/capybara_mock/blob/master/CODE_OF_CONDUCT.md).
172
+
173
+ ## License
174
+
175
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
176
+
177
+ ## Code of Conduct
178
+
179
+ Everyone interacting in the CapybaraMock project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/railsware/capybara_mock/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require 'rubocop/rake_task'
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CapybaraMock
4
+ module Interceptor
5
+ # Base interceptor class
6
+ class Base
7
+ attr_reader :stubs, :unstubbed_requests
8
+
9
+ def initialize
10
+ @stubs = []
11
+ @unstubbed_requests = []
12
+ end
13
+
14
+ private
15
+
16
+ def stub_for(request)
17
+ @stubs.find do |stub|
18
+ stub.match?(request)
19
+ end
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,94 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'uri'
4
+ require 'rack/utils'
5
+
6
+ module CapybaraMock
7
+ module Interceptor
8
+ # Cuprite interceptor
9
+ class Cuprite < Base
10
+ # @see https://github.com/chromium/chromium/blob/main/net/http/http_status_code_list.h
11
+ SUPPORTED_STATUS_CODES = [
12
+ 100,
13
+ 101,
14
+ 103,
15
+ *200..206,
16
+ 300,
17
+ 301,
18
+ 302,
19
+ 303,
20
+ 304,
21
+ 305,
22
+ 307,
23
+ 308,
24
+ *400..418,
25
+ 425,
26
+ 429,
27
+ *500..505
28
+ ].freeze
29
+
30
+ STATUS_CODE_HEADER_NAME = 'X-Mock-Response-Status'
31
+
32
+ private
33
+
34
+ def initialize(capybara_session)
35
+ super()
36
+ capybara_session.driver.browser.tap do |browser|
37
+ browser.network.intercept
38
+ browser.on(:request) { |request| call(request) }
39
+ end
40
+ end
41
+
42
+ def call(cuprite_request)
43
+ request = from_cuprite_request(cuprite_request)
44
+ stub = stub_for(request)
45
+ if stub
46
+ response = stub.call(request)
47
+ emulate_status_code!(response)
48
+ cuprite_response = to_cuprite_response(response)
49
+ cuprite_request.respond(**cuprite_response)
50
+ else
51
+ unstubbed_requests.push(request)
52
+ cuprite_request.continue
53
+ end
54
+ rescue Exception => e # rubocop:disable Lint/RescueException
55
+ warn e
56
+ warn e.backtrace
57
+ raise e
58
+ end
59
+
60
+ def from_cuprite_request(request)
61
+ {
62
+ method: request.method,
63
+ url: URI(request.url).tap { |uri| uri.query = nil }.to_s,
64
+ query: Rack::Utils.parse_query(URI(request.url).query),
65
+ headers: request.headers,
66
+ body: request.instance_variable_get(:@request)['postData']
67
+ }
68
+ end
69
+
70
+ # Emulate status codes if it does not yet supported by CDP.
71
+ # It uses more generic status code and pass actual status code in header.
72
+ # Requires some client side middleware to finish emulation.
73
+ #
74
+ # @example
75
+ # [422, {}, 'BODY'] => [400, {'X-Mock-Response-Status' => 422}, 'BODY']
76
+ # [511, {}, 'BODY'] => [500, {'X-Mock-Response-Status' => 511}, 'BODY']
77
+ def emulate_status_code!(response)
78
+ status = response[0]
79
+ return if SUPPORTED_STATUS_CODES.include?(status)
80
+
81
+ response[0] = status.div(100) * 100
82
+ response[1] = response[1].merge(STATUS_CODE_HEADER_NAME => status.to_s)
83
+ end
84
+
85
+ def to_cuprite_response(response)
86
+ {
87
+ responseCode: response[0],
88
+ responseHeaders: response[1],
89
+ body: response[2]
90
+ }.compact
91
+ end
92
+ end
93
+ end
94
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'capybara_mock'
4
+
5
+ RSpec.configure do |config|
6
+ config.after(:each, type: :feature) do
7
+ CapybaraMock.reset!
8
+ end
9
+ end
@@ -0,0 +1,83 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'rack'
4
+ require 'json'
5
+
6
+ module CapybaraMock
7
+ # Stub DSL
8
+ class Stub
9
+ def initialize(method, url)
10
+ @method = method.to_s.upcase
11
+ @url = url
12
+ with
13
+ to_return
14
+ end
15
+
16
+ def with(query: {}, headers: {}, body: nil)
17
+ @query = query
18
+ @headers = headers
19
+ @body = body
20
+ self
21
+ end
22
+
23
+ def to_return(status: 200, headers: {}, body: '', &block)
24
+ @response = block || [status, headers, body]
25
+ self
26
+ end
27
+
28
+ def call(request)
29
+ if @response.respond_to?(:call)
30
+ @response.call(**request)
31
+ else
32
+ @response
33
+ end
34
+ end
35
+
36
+ def match?(request)
37
+ match_method?(request) &&
38
+ match_url?(request) &&
39
+ match_query?(request) &&
40
+ match_headers?(request) &&
41
+ match_body?(request)
42
+ end
43
+
44
+ def match_method?(request)
45
+ @method == request[:method]
46
+ end
47
+
48
+ def match_url?(request)
49
+ if @url.is_a?(Regexp)
50
+ @url.match?(request[:url])
51
+ else
52
+ @url == request[:url]
53
+ end
54
+ end
55
+
56
+ def match_query?(request)
57
+ @query == request[:query].slice(*@query.keys)
58
+ end
59
+
60
+ def match_headers?(request)
61
+ @headers == request[:headers].slice(*@headers.keys)
62
+ end
63
+
64
+ def match_body?(request)
65
+ return true unless @body
66
+
67
+ decode_body(@body) == decode_body(request[:body])
68
+ end
69
+
70
+ private
71
+
72
+ def decode_body(body)
73
+ case @headers['Content-Type']
74
+ when %r{application/x-www-form-urlencoded}
75
+ Rack::Utils.parse_nested_query(body)
76
+ when %r{application/json}
77
+ JSON.parse(body)
78
+ else
79
+ body
80
+ end
81
+ end
82
+ end
83
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CapybaraMock
4
+ VERSION = '0.1.0'
5
+ end
@@ -0,0 +1,132 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'capybara_mock/version'
4
+ require_relative 'capybara_mock/stub'
5
+ require_relative 'capybara_mock/interceptor/base'
6
+ require_relative 'capybara_mock/interceptor/cuprite'
7
+
8
+ # ## CapybaraMock
9
+ #
10
+ # Mock capybara browser http requests.
11
+ #
12
+ # @example Stub external requests using `stub_request`
13
+ #
14
+ # CapybaraMock
15
+ # .stub_request(:get, 'http://example.com')
16
+ # .to_return(status: 200, headers: {}, body: 'Hello')
17
+ #
18
+ # @example Stub internal requests using `stub_path``
19
+ #
20
+ # CapybaraMock
21
+ # .stub_path(:get, '/api/user/101')
22
+ # .to_return(status: 200, headers: {}, body: 'Hello')
23
+ #
24
+ # @example More strict stub
25
+ #
26
+ # CapybaraMock
27
+ # .stub_request(:get, 'http://example.com')
28
+ # .with(
29
+ # query: {
30
+ # token: '12345678'
31
+ # },
32
+ # headers: {
33
+ # 'Authorization' => 'Bearer 12345678',
34
+ # 'Content-Type' => 'application/json'
35
+ # },
36
+ # body: {
37
+ # message: 'ping'
38
+ # }.to_json
39
+ # ).to_return(
40
+ # status: 200,
41
+ # headers: {
42
+ # 'Content-Type' => 'application/json'
43
+ # },
44
+ # body: {
45
+ # message: 'pong'
46
+ # }.to_json
47
+ # )
48
+ #
49
+ # @example Dynamic stub based on actual request
50
+ #
51
+ # CapybaraMock.stub_request(:get, /example/).to_return do |query:, **|
52
+ # state = query['state']
53
+ # [200, {'Location' => "http://localhost/foo?state={state}"}, '']
54
+ # end
55
+ module CapybaraMock
56
+ class Error < StandardError; end
57
+
58
+ class << self
59
+ # Stub capybara request for current session using path.
60
+ #
61
+ # @param method [String]
62
+ # @param path [String]
63
+ # @return [CapybaraMock::Stub]
64
+ def stub_path(method, path, &block)
65
+ url = File.join(capybara_session.server.base_url, path)
66
+ stub_request(method, url, &block)
67
+ end
68
+
69
+ # Stub capybara request for current session using url.
70
+ # It also initialize interceptor for current session on first stub.
71
+ #
72
+ # @param method [String]
73
+ # @param url [String]
74
+ # @return [CapybaraMock::Stub]
75
+ def stub_request(method, url, &block)
76
+ Stub.new(method, url, &block).tap do |stub|
77
+ interceptor.stubs << stub
78
+ end
79
+ end
80
+
81
+ # Remove capybara stub from current session.
82
+ #
83
+ # @param stub [CapybaraMock::Stub]
84
+ def remove_stub(stub)
85
+ interceptor.stubs.delete(stub)
86
+ end
87
+
88
+ # Clear all current session stubs
89
+ def clear_stubs
90
+ interceptor.stubs.clear
91
+ end
92
+
93
+ # Save unstubbed requests to path.
94
+ def save_unstubbed_requests(path)
95
+ return false unless @interceptor && @interceptor.unstubbed_requests.present?
96
+
97
+ File.open(path, 'w') do |f|
98
+ @interceptor.unstubbed_requests.each do |request|
99
+ f.puts "#{request[:method]} #{request[:url]} #{request[:query]}"
100
+ request[:headers].each do |k, v|
101
+ f.puts "#{k}: #{v}"
102
+ end
103
+ f.puts request[:body]
104
+ f.puts
105
+ end
106
+ end
107
+
108
+ true
109
+ end
110
+
111
+ # Reset capybara mock interceptor.
112
+ def reset!
113
+ @interceptor = nil
114
+ end
115
+
116
+ private
117
+
118
+ def interceptor
119
+ @interceptor ||=
120
+ case capybara_session.driver.class.name
121
+ when 'Capybara::Cuprite::Driver'
122
+ CapybaraMock::Interceptor::Cuprite.new(capybara_session)
123
+ else
124
+ raise "Capybara driver is not supported: #{capybara_session.driver.class}"
125
+ end
126
+ end
127
+
128
+ def capybara_session
129
+ Capybara.current_session
130
+ end
131
+ end
132
+ end
metadata ADDED
@@ -0,0 +1,76 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: capybara_mock
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Railsware Products Studio LLC
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2022-12-12 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rack
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: 2.2.0
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: 2.2.0
27
+ description: CapybaraMock
28
+ email:
29
+ - support@mailtrap.io
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - ".rspec"
35
+ - ".rubocop.yml"
36
+ - CHANGELOG.md
37
+ - CODE_OF_CONDUCT.md
38
+ - Gemfile
39
+ - Gemfile.lock
40
+ - LICENSE.txt
41
+ - README.md
42
+ - Rakefile
43
+ - lib/capybara_mock.rb
44
+ - lib/capybara_mock/interceptor/base.rb
45
+ - lib/capybara_mock/interceptor/cuprite.rb
46
+ - lib/capybara_mock/rspec.rb
47
+ - lib/capybara_mock/stub.rb
48
+ - lib/capybara_mock/version.rb
49
+ homepage: https://github.com/railsware/capybara_mock
50
+ licenses:
51
+ - MIT
52
+ metadata:
53
+ homepage_uri: https://github.com/railsware/capybara_mock
54
+ source_code_uri: https://github.com/railsware/capybara_mock
55
+ changelog_uri: https://github.com/railsware/capybara_mock/blob/main/CHANGELOG.md
56
+ rubygems_mfa_required: 'true'
57
+ post_install_message:
58
+ rdoc_options: []
59
+ require_paths:
60
+ - lib
61
+ required_ruby_version: !ruby/object:Gem::Requirement
62
+ requirements:
63
+ - - ">="
64
+ - !ruby/object:Gem::Version
65
+ version: 2.7.0
66
+ required_rubygems_version: !ruby/object:Gem::Requirement
67
+ requirements:
68
+ - - ">="
69
+ - !ruby/object:Gem::Version
70
+ version: '0'
71
+ requirements: []
72
+ rubygems_version: 3.2.15
73
+ signing_key:
74
+ specification_version: 4
75
+ summary: CapybaraMock
76
+ test_files: []