### Default WebValve Configuration Source: https://github.com/betterment/webvalve/blob/main/README.md This is an example of the `config/webvalve.rb` file generated by the install command. It shows how to register services and allow URLs. ```ruby # config/webvalve.rb # # register services # # WebValve.register "FakeBank" # WebValve.register "FakeExample", url: "https://api.example.org" # # # add urls to allowlist # # WebValve.allow_url "https://example.com" ``` -------------------------------- ### Non-Rails WebValve Setup Example Source: https://context7.com/betterment/webvalve/llms.txt Demonstrates how to set up and use WebValve in a non-Rails Ruby application, such as a Sinatra app, with manual configuration and service registration. ```ruby # app.rb (Sinatra example) require 'sinatra' require 'webvalve' require_relative 'webvalve/fake_twitter' require_relative 'config/webvalve' WebValve.setup get '/' do # HTTP requests to registered services are now intercepted response = Net::HTTP.get(URI('http://faketwitter.test/')) "Twitter says: #{response}" end # config/webvalve.rb require 'webvalve' require_relative '../webvalve/fake_twitter' WebValve.register 'FakeTwitter', url: 'http://faketwitter.test' # webvalve/fake_twitter.rb class FakeTwitter < WebValve::FakeService get '/' do json hello: 'world' end get '/tweets' do json tweets: [ { id: 1, text: 'Hello from fake Twitter!' } ] end end ``` -------------------------------- ### Example FakeService Implementation Source: https://github.com/betterment/webvalve/blob/main/README.md This is an example of a `FakeService` implementation. Define your routes within the class. You can toggle the service on via an environment variable. ```ruby # webvalve/fake_bank.rb class FakeBank < WebValve::FakeService # # define your routes here # # get '/widgets' do # json result: 'it works!' # end # # # toggle this service on via ENV # # export BANK_ENABLED=true end ``` -------------------------------- ### Install WebValve Source: https://context7.com/betterment/webvalve/llms.txt Add the gem to your Gemfile and run the installation generator to set up the configuration. ```ruby # Gemfile gem 'webvalve' ``` ```bash # Install WebValve and create config file bundle install rails generate webvalve:install ``` -------------------------------- ### WebValve Install Generator Source: https://github.com/betterment/webvalve/blob/main/README.md Run this command to generate the initial WebValve configuration file in your config directory. ```bash $ rails generate webvalve:install ``` -------------------------------- ### Generate WebValve Install Files Source: https://context7.com/betterment/webvalve/llms.txt Generates the WebValve configuration file and directory for storing fake service implementations in a Rails application. ```bash # Generate WebValve configuration rails generate webvalve:install # Creates: # - config/webvalve.rb (configuration file) # - webvalve/.keep (directory for fake services) ``` -------------------------------- ### Add WebValve to Gemfile Source: https://github.com/betterment/webvalve/blob/main/README.md Add this line to your Gemfile to include WebValve in your project. Run `bundle install` afterwards. ```ruby gem 'webvalve' ``` -------------------------------- ### RSpec Configuration for WebValve Source: https://github.com/betterment/webvalve/blob/main/README.md Include `webvalve/rspec` in your `spec_helper.rb` to enable WebValve's RSpec integration. This ensures proper setup and teardown for tests. ```ruby # spec/spec_helper.rb require 'webvalve/rspec' ``` -------------------------------- ### WebValve Fake Service Generator Source: https://github.com/betterment/webvalve/blob/main/README.md Use this generator to create a new fake service file. For example, `rails generate webvalve:fake_service Bank` will create `fake_bank.rb`. ```bash $ rails generate webvalve:fake_service Bank ``` -------------------------------- ### WebMock Network Connection Error Example Source: https://github.com/betterment/webvalve/blob/main/README.md When real HTTP connections are disabled by default, attempting to access an unregistered URL will result in a `WebMock::NetConnectNotAllowedError`. The error message provides a snippet to stub the request. ```ruby irb(main):007:0> Net::HTTP.get(URI('http://bank.test')) WebMock::NetConnectNotAllowedError: Real HTTP connections are disabled. Unregistered request: GET http://bank.test/ with headers {"Accept"=>"*", "User-Agent"=>"Ruby"} You can stub this request with the following snippet: stub_request(:get, "http://bank.test/"). with(:headers => {'Accept'=>'*/*', 'User-Agent'=>'Ruby'}). to_return(:status => 200, :body => "", :headers => {}) ``` -------------------------------- ### WebValve.setup Source: https://context7.com/betterment/webvalve/llms.txt Initializes WebValve and activates HTTP interception. ```APIDOC ## WebValve.setup ### Description Initializes WebValve and activates HTTP interception based on the current environment and configuration. Must be called manually for non-Rails applications. ``` -------------------------------- ### Enable Actual Service Environment Variable Source: https://github.com/betterment/webvalve/blob/main/README.md To connect to the actual service instead of the fake one, set the corresponding `_ENABLED` environment variable. Note that the application may need to be restarted. ```bash export BANK_ENABLED=true ``` -------------------------------- ### Environment Variables for WebValve Control Source: https://context7.com/betterment/webvalve/llms.txt Demonstrates how to use environment variables to control WebValve behavior, including service URLs, enabling/disabling services, and global control. ```bash # Service URL configuration (convention: {SERVICE}_API_URL) export BANK_API_URL='http://bank.test' export PAYMENT_API_URL='https://api.payment.dev' # Enable real service connections (bypass fake) export BANK_ENABLED=true # Disable specific service (use fake even when allowing by default) export PAYMENT_ENABLED=false # Global WebValve control (for non-dev/test environments) export WEBVALVE_ENABLED=true # Control default service behavior in non-dev/test environments # When true: services default to enabled (real connections) # When false: services default to disabled (use fakes) export WEBVALVE_SERVICE_ENABLED_DEFAULT=false ``` -------------------------------- ### Registering a Fake Service in Configuration Source: https://github.com/betterment/webvalve/blob/main/README.md After generating a fake service, ensure it is registered in your `config/webvalve.rb` file. ```ruby # config/webvalve.rb WebValve.register "FakeBank" ``` -------------------------------- ### Registering Fake Services with Regular Expressions Source: https://github.com/betterment/webvalve/blob/main/README.md Use regular expressions to define dynamic URLs for fake services, offering the most flexible pattern matching. This method does not support ENV var detection. ```ruby WebValve.register FakeBank, url: %r{\Ahttp://mybank.com(/.*)?\z} ``` -------------------------------- ### Implement Fake Services Source: https://context7.com/betterment/webvalve/llms.txt Create a fake service by extending WebValve::FakeService and defining Sinatra-style routes to handle intercepted requests. ```ruby # webvalve/fake_bank.rb class FakeBank < WebValve::FakeService # GET endpoint returning JSON get '/accounts' do json accounts: [ { id: 1, name: 'Checking', balance: 1000.00 }, { id: 2, name: 'Savings', balance: 5000.00 } ] end # GET endpoint with path parameters get '/accounts/:id' do account_id = params[:id] json id: account_id, name: 'Checking', balance: 1000.00 end # POST endpoint with request body parsing post '/transfers' do request_body = JSON.parse(request.body.read) json( id: SecureRandom.uuid, from_account: request_body['from_account'], to_account: request_body['to_account'], amount: request_body['amount'], status: 'completed' ) end # Simulating error responses get '/accounts/:id/error' do status 500 json error: 'Internal server error', message: 'Service unavailable' end end ``` -------------------------------- ### Registering Fake Services with Wildcard URLs Source: https://github.com/betterment/webvalve/blob/main/README.md Register a fake service using a URL pattern that includes a wildcard '*' to match dynamic parts of the URL. This is an alternative to using environment variables for dynamic URLs. ```ruby WebValve.register FakeBank, url: "https://*.mybank.com" ``` -------------------------------- ### Registering Fake Services with Custom URLs Source: https://github.com/betterment/webvalve/blob/main/README.md Register a fake service with a custom URL, either by fetching it from an environment variable or by providing a constant string. This allows overriding default service endpoints. ```ruby # config/webvalve.rb # using an ENV variable WebValve.register FakeBank, url: ENV.fetch("SOME_CUSTOM_API_URL") # or with a constant value WebValve.register FakeBank, url: "https://some-service.com" ``` -------------------------------- ### Configuring Dynamic URLs with Wildcards Source: https://github.com/betterment/webvalve/blob/main/README.md Specify a wildcard '*' in the URL to match dynamic URL segments, such as subdomains. Note that '?' is not supported as a wildcard character. ```bash export BANK_API_URL=https://*.mybank.com/ ``` -------------------------------- ### Registering Fake Services with Addressable::Template Source: https://github.com/betterment/webvalve/blob/main/README.md Use Addressable::Template to define dynamic URLs for fake services, providing more complex pattern matching than simple wildcards. This method does not support ENV var detection. ```ruby WebValve.register FakeBank, url: Addressable::Template.new("http://mybank.com{/path*}{?query}") ``` -------------------------------- ### Initialize WebValve Source: https://context7.com/betterment/webvalve/llms.txt Manually activate WebValve interception for non-Rails applications. ```ruby # For non-Rails applications require 'webvalve' require_relative 'webvalve/fake_twitter' # Load configuration require_relative 'config/webvalve' # Activate WebValve interception WebValve.setup # Now HTTP requests to registered services will be intercepted response = Net::HTTP.get(URI('http://faketwitter.test/')) # => Routes to FakeTwitter service ``` -------------------------------- ### Generate Fake Service Class Source: https://context7.com/betterment/webvalve/llms.txt Generates a new fake service class and automatically registers it in the WebValve configuration file. ```bash # Generate a fake service for Bank API rails generate webvalve:fake_service Bank # Creates webvalve/fake_bank.rb: # class FakeBank < WebValve::FakeService # # define your routes here # # # # get '/widgets' do # # json result: 'it works!' # # end # # # # export BANK_API_URL='http://whatever.dev' # # export BANK_ENABLED=true # end # Automatically adds to config/webvalve.rb: # WebValve.register "FakeBank" ``` -------------------------------- ### WebValve::FakeService Source: https://context7.com/betterment/webvalve/llms.txt Base class for creating fake service implementations using Sinatra. ```APIDOC ## WebValve::FakeService ### Description Base class for creating fake service implementations. Extends Sinatra::Base and provides JSON response helpers for mocking API endpoints. ### Methods - **get** (path, block) - Defines a GET route. - **post** (path, block) - Defines a POST route. ### Response - **json** (Object) - Helper method to return JSON responses. ``` -------------------------------- ### Set Service Base URL Environment Variable Source: https://github.com/betterment/webvalve/blob/main/README.md Define an environment variable for the base URL of the service you are faking. This is required for requests to be routed correctly. ```bash export BANK_API_URL='http://bank.test' ``` -------------------------------- ### Register Fake Services Source: https://context7.com/betterment/webvalve/llms.txt Register a service class with WebValve, specifying the URL via environment variables, explicit strings, or advanced matching patterns. ```ruby # config/webvalve.rb # Basic registration - uses BANK_API_URL environment variable WebValve.register "FakeBank" # With explicit URL WebValve.register "FakeBank", url: "https://api.bank.com" # Using environment variable for custom URL WebValve.register "FakeBank", url: ENV.fetch("SOME_CUSTOM_API_URL") # Dynamic URL with wildcard for multi-tenant services WebValve.register "FakeBank", url: "https://*.mybank.com" # Using Addressable::Template for complex URL patterns WebValve.register "FakeBank", url: Addressable::Template.new("http://mybank.com{/path*}{?query}") # Using Regexp for advanced URL matching WebValve.register "FakeBank", url: %r{\Ahttp://mybank.com(/.*)?\z} ``` -------------------------------- ### Allowlist External URLs Source: https://context7.com/betterment/webvalve/llms.txt Permit real HTTP connections to specific external services while WebValve is active. ```ruby # config/webvalve.rb # Allow specific URLs to bypass interception WebValve.allow_url "https://api.stripe.com" WebValve.allow_url "https://hooks.slack.com" # Allow URLs with wildcards WebValve.allow_url "https://*.amazonaws.com" # Multiple allowlisted URLs WebValve.allow_url "https://cdn.example.com" WebValve.allow_url "https://analytics.example.com" ``` -------------------------------- ### WebValve.reset! Source: https://context7.com/betterment/webvalve/llms.txt Resets the WebValve state by clearing registered services and allowlisted URLs. ```APIDOC ## WebValve.reset! ### Description Clears all registered services and allowlisted URLs, then re-runs setup. Used to ensure test isolation between test cases. ``` -------------------------------- ### Clear WebValve Configuration Source: https://context7.com/betterment/webvalve/llms.txt Clears all registered services, allowlisted, and stubbed URLs. Useful for completely resetting WebValve state. ```ruby # Clear all WebValve configuration WebValve.clear! # Manually register new services WebValve.register "FakePayment", url: "https://payment.test" # Then setup when ready WebValve.setup ``` -------------------------------- ### WebValve.allow_url Source: https://context7.com/betterment/webvalve/llms.txt Adds a URL to the allowlist to permit real HTTP connections while WebValve is active. ```APIDOC ## WebValve.allow_url ### Description Adds a URL to the allowlist, permitting real HTTP connections to that URL while WebValve is active. ### Parameters - **url** (String) - Required - The URL or URL pattern to allow. ``` -------------------------------- ### WebValve Integration with WebMock for Testing Source: https://context7.com/betterment/webvalve/llms.txt Shows how to use WebMock within RSpec tests to override fake service behavior for specific scenarios, such as handling errors or timeouts. ```ruby # spec/features/bank_integration_spec.rb require 'spec_helper' RSpec.describe 'Bank Integration' do it 'handles successful account retrieval' do # Uses the default FakeBank routes response = Faraday.get('http://bank.test/accounts') expect(response.status).to eq(200) end it 'handles 404 errors gracefully' do # Override with WebMock for specific test scenario stub_request(:get, 'http://bank.test/accounts/999') .to_return(status: 404, body: { error: 'Account not found' }.to_json) response = Faraday.get('http://bank.test/accounts/999') expect(response.status).to eq(404) expect(JSON.parse(response.body)['error']).to eq('Account not found') end it 'handles network timeouts' stub_request(:get, 'http://bank.test/slow-endpoint') .to_timeout expect { Faraday.get('http://bank.test/slow-endpoint') }.to raise_error(Faraday::ConnectionFailed) end end ``` -------------------------------- ### Mocking HTTP Responses in RSpec Tests Source: https://github.com/betterment/webvalve/blob/main/README.md Use WebMock to stub specific HTTP requests and define their responses, such as returning a 404 status with a nil body. This is useful for testing how your application handles specific error conditions. ```ruby # in an rspec test... it 'handles 404s by returning nil' do fake_req = stub_request('http://bank.test/some/url/1234') .to_return(status: 404, body: nil) response = Faraday.get 'http://bank.test/some/url/1234' expect(response.body).to be_nil expect(fake_req).to have_been_requested end ``` -------------------------------- ### WebValve.register Source: https://context7.com/betterment/webvalve/llms.txt Registers a fake service class with WebValve to intercept HTTP requests directed at a specific URL or pattern. ```APIDOC ## WebValve.register ### Description Registers a fake service class with WebValve for HTTP request interception. The service class name must be provided as a string. The URL can be specified explicitly or derived from environment variables. ### Parameters - **service_name** (String) - Required - The name of the fake service class. - **options** (Hash) - Optional - Configuration options including 'url' for the service endpoint. ``` -------------------------------- ### Reset WebValve State Source: https://context7.com/betterment/webvalve/llms.txt Clear registered services and allowlisted URLs to ensure test isolation between runs. ```ruby # spec/spec_helper.rb require 'webvalve/rspec' # Automatically configures reset! around each test # Or configure manually for other test frameworks RSpec.configure do |config| config.around :each do |example| WebValve.reset! example.run end end ``` -------------------------------- ### Check if WebValve is Enabled Source: https://context7.com/betterment/webvalve/llms.txt Returns true if WebValve is enabled. It's always enabled in development and test environments, otherwise controlled by the WEBVALVE_ENABLED environment variable. ```ruby # Check if WebValve is active if WebValve.enabled? puts "WebValve is intercepting HTTP requests" else puts "WebValve is disabled, real HTTP connections allowed" end # Environment variable control (production/staging) # export WEBVALVE_ENABLED=true # export WEBVALVE_ENABLED=1 # export WEBVALVE_ENABLED=t ``` -------------------------------- ### Configure RSpec Retry and WebValve Reset Source: https://context7.com/betterment/webvalve/llms.txt Configures RSpec to retry tests that fail and resets WebValve state before each test. ```ruby RSpec.configure do |config| config.around :each do |ex| ex.run_with_retry retry: 2 end config.around :each do |ex| WebValve.reset! ex.run end end ``` -------------------------------- ### RSpec Configuration with rspec-retry Source: https://github.com/betterment/webvalve/blob/main/README.md If using `rspec-retry`, manually register the `WebValve.reset!` around hook to ensure WebValve is reset for each retry, preventing state leakage between retries. ```ruby # spec/[rails|spec]_helper.rb # your require lines omitted ... require 'webmock/rspec' # set up webmock lifecycle hooks - required RSpec.configure do |config| # your config lines omitted ... config.around :each do |ex| ex.run_with_retry retry: 2 end config.around :each do |ex| WebValve.reset! ex.run end end ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.