• Stars
    star
    103
  • Rank 321,862 (Top 7 %)
  • Language
    Crystal
  • License
    MIT License
  • Created about 9 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Mock HTTP::Client

webmock.cr

Build Status

Library for stubbing HTTP::Client requests in Crystal.

Inspired by webmock ruby gem.

Installation

Add it to shards.yml:

development_dependencies:
  webmock:
    github: manastech/webmock.cr
    branch: master

Usage

require "webmock"

By requiring webmock unregistered HTTP::Client requests will raise an exception. If you still want to execute real requests, do this:

WebMock.allow_net_connect = true

Stub request based on uri only and with the default response

WebMock.stub(:any, "www.example.com")

response = HTTP::Client.get("http://www.example.com")
response.body        #=> ""
response.status_code #=> 200

Stub requests based on method, uri, body, headers and custom response

WebMock.stub(:post, "www.example.com/foo").
  with(body: "abc", headers: {"Content-Type" => "text/plain"}).
  to_return(status: 500, body: "oops", headers: {"X-Error" => "true"})

response = HTTP::Client.post("http://www.example.com/foo",
                               body: "abc",
                               headers: HTTP::Headers{"Content-Type" => "text/plain"})
response.status_code        #=> 500
response.body               #=> "oops"
response.headers["X-Error"] #=> "true"

# Executing the same request gives the same response
response = HTTP::Client.post("http://www.example.com/foo",
                               body: "abc",
                               headers: HTTP::Headers{"Content-Type" => "text/plain"})
response.body               #=> "oops"

Stub requests based on query string

WebMock.stub(:get, "www.example.com").
  with(query: {"page" => "1", "count" => "10"})

response = HTTP::Client.get("http://www.example.com?count=10&page=1")
response.status_code #=> 200

Stub requests and provide a block for the response

Your block will be called and passed the HTTP::Request, allowing you to construct a response dynamically based upon the request.

WebMock.stub(:post, "www.example.com/foo").to_return do |request|
  headers = HTTP::Headers.new.merge!({ "Content-length" => request.body.to_s.length })
  HTTP::Client::Response.new(418, body: request.body.to_s.reverse, headers: headers)
end

response = HTTP::Client.post("http://www.example.com/foo",
                             body: "abc",
                             headers: HTTP::Headers{"Content-Type" => "text/plain"})
response.status_code               #=> 418
response.body                      #=> "cba"
response.headers["Content-length"] #=> "3"

response = HTTP::Client.post("http://www.example.com/foo",
                             body: "olleh",
                             headers: HTTP::Headers{"Content-Type" => "text/plain"})
response.status_code               #=> 418
response.body                      #=> "hello"
response.headers["Content-length"] #=> "5"

Resetting

WebMock.reset

This clears all stubs and sets allow_net_connect to false.

To execute this automatically before each spec, you can do:

Spec.before_each &->WebMock.reset

Or, for individual specs you can use WebMock.wrap and a block to make sure WebMock is reset at the end of a spec:

WebMock.wrap do
  WebMock.stub(:get, "www.example.com").to_return(body: "Example")

  HTTP::Client.get("http://www.example.com").body #=> "Example"
end

HTTP::Client.get("http://www.example.com") # Raises WebMock::NetConnectNotAllowedError

Todo

Bring more features found in the webmock ruby gem.

Contributing

  1. Fork it ( https://github.com/manastech/webmock.cr/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

More Repositories

1

crystal_ruby

Write Ruby extensions in Crystal
Crystal
99
star
2

frank

A small Sinatra clone for Crystal
Crystal
77
star
3

middleman-search

LunrJS-based search for Middleman
Ruby
58
star
4

handbook

Manas Handbook
CSS
22
star
5

crystal_slack

Parse Slack slash commands or send incoming web hooks from Crystal
Crystal
20
star
6

crocoa

Cocoa for crystal
Crystal
20
star
7

benchy

A tool to perform benchmarks
Crystal
15
star
8

rancher-autoredeploy

Autoredeploy images on Docker Hub webhook pushes in Rancher
Crystal
15
star
9

includes-count

Ruby
14
star
10

crystal_redis

Redis client for Crystal
Crystal
14
star
11

atom-crystal-tools

Atom package that integrates crystal tools
CoffeeScript
10
star
12

listings

Simple creation of listings in rails applications
Ruby
5
star
13

fig-dns

DNS server for Docker containers managed by Fig
JavaScript
5
star
14

licit

Apply public licenses to files in ruby projects
Ruby
5
star
15

conan

Fast and lightweight framework to collect system metrics
Crystal
5
star
16

erl_csv_generator

Generate CSV files in Erlang
Erlang
4
star
17

mitm.cr

HTTP/S proxy server to intercept and inspect calls
Crystal
4
star
18

biocrystal

BioCrystal
Crystal
4
star
19

cafa5

Jupyter Notebook
4
star
20

erl-dbmodel

Erlang
3
star
21

d3-charts

Experiments on charts with D3
JavaScript
3
star
22

triangles

Counting triangles problem solved in May 2009
Java
2
star
23

dist

Generate packages to distribute Rails applications
Ruby
2
star
24

env_rails

Set Rails configuration parameters using environment variables
Ruby
2
star
25

pill-input

html based input with text and pills
JavaScript
2
star
26

rails-view_components

Simple library for building view components in Rails
Ruby
1
star
27

de-bee

De-Bee gives you a really simple way to deal with "I owe you"s and expense sharing for groups.
Python
1
star
28

knockout_forms-rails

Knockoutjs powered form builder for Rails
Ruby
1
star
29

rancher-zabbix-agent

Shell
1
star
30

stable-rails

Ruby
1
star
31

svg-input

SVG based input with pills support
JavaScript
1
star
32

ci-docker-builder

Scripts to facilitate building Docker images with right tags
Shell
1
star
33

cet-instagram

Utilitario para contactar inscriptas en Comunidad CET vĂ­a Instagram
Python
1
star
34

crystal-circleci-orb

Common CircleCI tasks for the Crystal programming language
1
star
35

javadrone

AR.Drone Java API
Java
1
star
36

crystal-ml

A classic machine learning library for Crystal programming language
Crystal
1
star
37

crystal_brium

Access Brium's API using Crystal
Crystal
1
star