• Stars
    star
    51
  • Rank 550,001 (Top 12 %)
  • Language
    Crystal
  • License
    MIT License
  • Created about 9 years ago
  • Updated about 4 years ago

Reviews

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

Repository Details

General purpose mocking library for Crystal.

mocks Build Status

General purpose mocking library for Crystal.

Installation

Add it to shard.yml:

dependencies:
  mocks:
    github: waterlink/mocks.cr
    version: ~> 0.9

This shard requires version of Crystal minimum 0.13.0.

Usage

require "mocks"

Usage with spec library

require "mocks/spec"

This will automatically register Mocks.reset hooks in before_each and after_each. Additionally it makes allow, receive and have_received available in global scope.

If you need all of macros (such as: create_mock, create_double, double, instance_double, etc.) to be available in global scope use include ::Mocks::Macro.

Usage with spec2 library

First add spec2-mocks to your dependencies:

dependencies:
  mocks:
    github: waterlink/mocks.cr
  spec2:
    github: waterlink/spec2.cr
  spec2-mocks:
    github: waterlink/spec2-mocks.cr

Run crystal deps update and do:

require "spec2-mocks"

This should be enough to start using mocks together with spec2.

Partial double

class Example
  def say_hello(name)
    "hey, #{name}"
  end
end

Mocks.create_mock Example do
  mock say_hello(name)
  # or
  # mock instance.say_hello(name)
end

example = Example.new
allow(example).to receive(say_hello("world")).and_return("hello, world!")

example.say_hello("world")    #=> "hello, world!"
example.say_hello("john")     #=> "hey, john"

If you want to mock operators or setters, syntax is pretty straightforward:

# setter
mock instance.greeting = value
# or
mock instance.greeting=(value)

# equals
mock instance == other
# or
mock instance.==(other)

Class methods

Just use mock self.method_name(args..)

Mocks.create_mock Example do
  mock self.hello_world(greeting)
end

allow(Example).to receive(self.hello_world("aloha")).and_return("aloha (as 'hello'), world!")
Example.hello_world("hey")         # => "hey, world!"                   (original was called)
Example.hello_world("aloha")       # => "aloha (as 'hello'), world!"    (mock was called)

Module methods

Just use mock self.method_name(args..)

module Example
  def self.hello_world(greeting)
    greeting
  end
end

Mocks.create_module_mock Example do
  mock self.hello_world(greeting)
end

allow(Example).to receive(self.hello_world("aloha")).and_return("aloha (as 'hello'), world!")

Mocking Struct

struct Example
  def now
    Time.now
  end
end

Mocks.create_struct_mock Example do
  mock now
end

example = Example.new
allow(example).to receive(now).and_return(Time.new(2014, 12, 22))

Double

Caution: doubles require return types.

Mocks.create_double "OtherExample" do
  mock say_hello(name).as(String)
  mock greetings_count.as(Int64)

  # For setters and operators this is the only syntax allowed:
  # ( parenthesis are mandatory not to confuse Crystal's parser )
  mock (instance.greeting = value), String
  mock (instance == other), Bool
end

example = Mocks.double("OtherExample", returns(say_hello("world"), "hello world!"))
allow(example).to receive(instance.greeting=("hey")).and_return("hey")

example.say_hello("world")     #=> "hello world!"
example.say_hello("john")      #=> Mocks::UnexpectedMethodCall: #<Mocks::Doubles::OtherExample:0x109498F00> received unexpected method call say_hello["john"]

Instance double

After defining Example's mock with create_mock you can use it as an instance_double:

example = Mocks.instance_double(Example, returns(say_hello("world"), "hello, world!"))
allow(example).to receive(say_hello("sarah")).and_return("Hey, Sarah!")

example.say_hello("world")     #=> "hello world!"
example.say_hello("sarah")     #=> "Hey, Sarah!"
example.say_hello("john")      #=> Mocks::UnexpectedMethodCall: #<Mocks::InstanceDoubles::Example:0x109498F00> received unexpected method call say_hello["john"]

Class double

After defining Example's mock with create_mock you can use it as a class_double:

example_class = Mocks.class_double(Example, returns(self.hello_world("aloha"), "aloha, world!"))
allow(example_class).to receive(self.hello_world("hi")).and_return("hey, world!")

example_class.hello_world("aloha")            # => "aloha, world!"
example_class.hello_world("hi")               # => "hey, world!"
example_class.hello_world("halo")             # => Mocks::UnexpectedMethodCall: Mocks::InstanceDoubles::Example received unexpected method call self.hello_world["halo"]

.new

It returns normal instance_double:

example_class = Mocks.class_double(Example)
example_class.new          # => #<Mocks::InstanceDoubles::Example:0x109498F00>

HaveReceived expectation (usage with stdlib spec)

example = Example.new
example.say("hello")
example.should have_received(say("hello"))   # passes
example.should have_received(say("hi"))      # fails

Development

After cloning the project:

cd mocks.cr
crystal deps   # install dependencies
crystal spec   # run specs

Just use normal TDD development style.

Contributing

  1. Fork it ( https://github.com/waterlink/mocks.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

Contributors

  • waterlink Oleksii Fedorov - creator, maintainer

More Repositories

1

rack-reverse-proxy

A Reverse Proxy for Rack
Ruby
194
star
2

active_record.cr

Active Record pattern implementation for Crystal.
Crystal
191
star
3

Challenge-Build-Your-Own-Array-In-Js

This is a challenge that will allow you to practice your logical, analytical and problem-solving skills. Additionally, by the end of it you’ll have much better command of arrays in javascript.
JavaScript
177
star
4

rspec-json_expectations

Set of matchers and helpers to allow you test your APIs responses like a pro.
Gherkin
138
star
5

spec2.cr

Enhanced `spec` testing library for [Crystal](http://crystal-lang.org/).
Crystal
103
star
6

crystal-mysql

Basic mysql bindings for crystal.
Crystal
32
star
7

timecop.cr

Mock with `Time.now` with the power of time travel, time freeze and time scale.
Crystal
19
star
8

refactoring-koans-js

Refactoring Koans to help you learn to refactor code smells in javascript
JavaScript
17
star
9

query.cr

Query abstraction for Crystal Language. Used by active_record.cr library.
Crystal
13
star
10

quick.cr

QuickCheck implementation for Crystal Language
Crystal
11
star
11

kotlin-spring-boot-mvc-starter

This is a starter repository for work with Kotlin on Back-end using Spring Boot 2 MVC, JdbcTemplate, Thymeleaf, Emails with Thymeleaf templates, Spring Security, Feature/UI tests using Fluentlenium, Clean Controller->Service->Repository pattern that is a sweet spot as your starting architecture. Includes a small demo in its source code.
Kotlin
11
star
12

postgres_adapter.cr

Postgres adapter for [active_record.cr](https://github.com/waterlink/active_record.cr). Uses [crystal-pg](https://github.com/will/crystal-pg) driver.
Crystal
9
star
13

spec2-mocks.cr

This library connects spec2.cr and mocks.cr, effectively enabling 'have_received' expectation for spec2.
Crystal
8
star
14

expand.cr

Crystal tool for macro debugging. Allows one to expand macro recursively.
Shell
6
star
15

mysql_adapter.cr

Mysql adapter for [active_record.cr](https://github.com/waterlink/active_record.cr). Uses [crystal-mysql library](https://github.com/waterlink/crystal-mysql)
Crystal
6
star
16

timestamp.cr

Timestamps in crystal-lang. Adds `.from_timestamp` and `#to_timestamp` methods to `Time`
Crystal
5
star
17

quizzykotlin

An example application for my free Getting Started With Kotlin Tutorial
Kotlin
4
star
18

rebecca

Simple database convenience wrapper for Go language.
Go
4
star
19

BuildYourOwnTestingFrameworkPart1

This is a source code for the first part of "Build Your Own Testing Framework" series
JavaScript
4
star
20

singleton.cr

Singleton library for Crystal Language.
Crystal
3
star
21

devpoll

devpoll - small web application for making polls written in http://crystal-lang.org/ (Crystal lang)
Crystal
3
star
22

aop

Very thin AOP gem for Ruby
Ruby
3
star
23

four-cycles-of-tdd-lightning-talk

Slides for my lightning talk: 4 Cycles of Test-Driven Development
HTML
3
star
24

money_tracking

CLI tool for tracking your expenses.
Ruby
2
star
25

restricted_struct

RestrictedStruct gem: create Struct-s with private or protected attributes
Ruby
2
star
26

contracts-rspec

Plugin for contracts.ruby that fixes issues with rspec-mocks.
Ruby
2
star
27

openproject-docker

Let OpenProject run in a docker container
Shell
2
star
28

race-conditions-testing-example

Kotlin
2
star
29

plugged

Library for writing extendable CLI applications for Golang.
Go
2
star
30

tspp_project

C++
2
star
31

messenger-ES6

JavaScript
1
star
32

goactor

Thin Actor implementation in Golang
Go
1
star
33

confident.ruby

Be confident and narrative when writing code in ruby
Ruby
1
star
34

secrets

Simple bash script to manage your secrets with symmetric key.
Shell
1
star
35

es-snapshot

This is a small script to make an elasticsearch snapshot. Tested with TDD in Bash in a very esoteric way.
Shell
1
star
36

crystal-blog

Simple blog in crystal using frank and active_record.cr
Crystal
1
star
37

cars-droid

Clojure
1
star
38

ShellTools

My bash shell tools. Unit-tested.
Shell
1
star
39

likes

Give it a list of people and their likings and it will tell what else could these people like. Ruby gem.
Ruby
1
star
40

docker-elasticsearch-kubernetes-aws

Docker image for elasticsearch with support for Kubernetes and AWS cloud
Shell
1
star
41

namegen.cr

This library provides facilities for generating random names/nicknames. Written in Crystal-Lang.
Crystal
1
star
42

stomp

Example game engine in Ruby. Uses Component Entity System + World paradigm.
Ruby
1
star
43

tdd-talk-ru

TDD talk (version in Russian, for Top-Engineer webinar). | Доклад о TDD, для вебинара Top-Engineer.
HTML
1
star
44

elm-todo

Simple ToDo application written in Elm lang. No backend (yet?).
Elm
1
star
45

explorative-tdd-talk

CSS
1
star
46

gas-template

Google Apps Script template for more comfortable development on local machine. Plus CI/CD included.
Shell
1
star
47

LoginSignupE2E

Example project for the blog post "Learning TDD with JS: End-to-End Testing". Implements Login and Signup for a web-application using TDD and E2E feature tests.
JavaScript
1
star
48

cars_api

Ruby
1
star
49

strong_ruby

Just playing around with strong typing in Ruby
Ruby
1
star
50

property-based-testing-talk

HTML
1
star
51

contracts-non_intrusive

Less intrusive version of Contracts DSL. Allows to use static/dynamic code analysis tools.
Ruby
1
star
52

recorder

Daemon that records all incoming HTTP request and allow to fetch them and put expectations on them. Useful for CLI tools testing.
Go
1
star