{"id":13878057,"url":"https://github.com/Qqwy/ruby-prop_check","last_synced_at":"2025-07-16T14:30:46.512Z","repository":{"id":44349205,"uuid":"192760059","full_name":"Qqwy/ruby-prop_check","owner":"Qqwy","description":"Property Testing library in Ruby","archived":false,"fork":false,"pushed_at":"2024-08-17T08:04:21.000Z","size":323,"stargazers_count":86,"open_issues_count":2,"forks_count":10,"subscribers_count":2,"default_branch":"main","last_synced_at":"2024-10-12T04:32:51.916Z","etag":null,"topics":["property-based-testing","property-testing","quickcheck","ruby"],"latest_commit_sha":null,"homepage":"https://rubygems.org/gems/prop_check","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Qqwy.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2019-06-19T15:34:26.000Z","updated_at":"2024-10-12T03:48:48.000Z","dependencies_parsed_at":"2023-11-08T12:24:34.964Z","dependency_job_id":"b76a5f41-f6b3-43c0-99a5-c0d219cadddb","html_url":"https://github.com/Qqwy/ruby-prop_check","commit_stats":{"total_commits":213,"total_committers":4,"mean_commits":53.25,"dds":"0.18309859154929575","last_synced_commit":"a7d2200ca90810f95d891c35d139e348257c0052"},"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Qqwy%2Fruby-prop_check","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Qqwy%2Fruby-prop_check/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Qqwy%2Fruby-prop_check/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Qqwy%2Fruby-prop_check/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Qqwy","download_url":"https://codeload.github.com/Qqwy/ruby-prop_check/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":225950751,"owners_count":17550309,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["property-based-testing","property-testing","quickcheck","ruby"],"created_at":"2024-08-06T08:01:38.675Z","updated_at":"2024-11-24T06:31:45.646Z","avatar_url":"https://github.com/Qqwy.png","language":"Ruby","funding_links":[],"categories":["Ruby","Advanced Ruby and Rails"],"sub_categories":["Advanced Ruby"],"readme":"# PropCheck\n\nPropCheck allows you to do Property Testing in Ruby.\n\n[![Gem](https://img.shields.io/gem/v/prop_check.svg)](https://rubygems.org/gems/prop_check)\n[![Ruby RSpec tests build status](https://github.com/Qqwy/ruby-prop_check/actions/workflows/run_tests.yaml/badge.svg)](https://github.com/Qqwy/ruby-prop_check/actions/workflows/run_tests.yaml)\n[![Maintainability](https://api.codeclimate.com/v1/badges/71897f5e6193a5124a53/maintainability)](https://codeclimate.com/github/Qqwy/ruby-prop_check/maintainability)\n[![RubyDoc](https://img.shields.io/badge/%F0%9F%93%9ARubyDoc-documentation-informational.svg)](https://www.rubydoc.info/github/Qqwy/ruby-prop_check/main/)\n\nIt features:\n\n- Generators for most common Ruby datatypes.\n- An easy DSL to define your own generators (by combining existing ones, as well as completely custom ones).\n- Shrinking to a minimal counter-example on failure.\n- Hooks to perform extra set-up/cleanup logic before/after every example case.\n\nIt requires _no_ external dependencies, and integrates well with all common test frameworks (see below).\n\n## What is PropCheck?\n\nPropCheck is a Ruby library to create unit tests which are simpler to write and more powerful when run, finding edge-cases in your code you wouldn't have thought to look for.\n\nIt works by letting you write tests that assert that something should be true for _every_ case, rather than just the ones you happen to think of.\n\n\nA normal unit test looks something like the following:\n\n1. Set up some data.\n2. Perform some operations on the data.\n3. Assert something about the result\n\nPropCheck lets you write tests which instead look like this:\n\n1. For all data matching some specification.\n2. Perform some operations on the data.\n3. Assert something about the result.\n\nThis is often called property-based testing. It was popularised by the Haskell library [QuickCheck](https://hackage.haskell.org/package/QuickCheck). \nPropCheck takes further inspiration from Erlang's [PropEr](https://hex.pm/packages/proper), Elixir's [StreamData](https://hex.pm/packages/stream_data) and Python's [Hypothesis](https://hypothesis.works/).\n\nIt works by generating arbitrary data matching your specification and checking that your assertions still hold in that case. If it finds an example where they do not, it takes that example and shrinks it down, simplifying it to find the smallest example that still causes the problem.\n\nWriting these kinds of tests usually consists of deciding on guarantees that your code should have -- properties that should always hold true, regardless of wat the world throws at you. Some examples are:\n\n- Your code should never crash.\n- If you remove an object, you can no longer see it\n- If you serialize and then deserialize a value, you get the same value back.\n\n\n## Implemented and still missing features\n\nBefore releasing v1.0, we want to finish the following:\n\n- [x] Finalize the testing DSL.\n- [x] Testing the library itself (against known 'true' axiomatically correct Ruby code.)\n- [x] Customization of common settings\n - [x] Filtering generators. \n  - [x] Customize the max. of samples to run.\n  - [x] Stop after a ludicrous amount of generator runs, to prevent malfunctioning (infinitely looping) generators from blowing up someone's computer.\n- [x] Look into customization of settings from e.g. command line arguments.\n- [x] Good, unicode-compliant, string generators.\n- [x] Filtering generator outputs.\n- [x] Before/after/around hooks to add setup/teardown logic to be called before/after/around each time a check is run with new data.\n- [x] Possibility to resize generators.\n- [x] `#instance` generator to allow the easy creation of generators for custom datatypes.\n- [x] Builtin generation of `Set`s\n- [x] Builtin generation of `Date`s, `Time`s and `DateTime`s.\n- [x] Configuration option to resize all generators given to a particular Property instance.\n- [x] A simple way to create recursive generators\n- [ ] A usage guide.\n\n## Nice-to-haves\n \n- Stateful property testing. If implemented at some point, will probably happen in a separate add-on library.\n\n\n## Installation\n\nAdd this line to your application's Gemfile:\n\n```ruby\ngem 'prop_check'\n```\n\nAnd then execute:\n\n    $ bundle\n\nOr install it yourself as:\n\n    $ gem install prop_check\n\n## Usage\n\n\n### Using PropCheck for basic testing\n\nPropcheck exposes the `forall` method.\nIt takes any number of generators as arguments (or keyword arguments), as well as a block to run.\nThe value(s) generated from the generator(s) passed to the `forall` will be given to the block as arguments.\n\nRaise an exception from the block if there is a problem. If there is no problem, just return normally.\n\n```ruby\nG = PropCheck::Generators\n# testing that Enumerable#sort sorts in ascending order\nPropCheck.forall(G.array(G.integer)) do |numbers|\n  sorted_numbers = numbers.sort\n  \n  # Check that no number is smaller than the previous number\n  sorted_numbers.each_cons(2) do |former, latter| \n    raise \"Elements are not sorted! #{latter} is \u003c #{former}\" if latter \u003e former\n  end\nend\n```\n\n\nHere is another example, using it inside a test case.\nHere we check if `naive_average` indeed always returns an integer for all arrays of numbers we can pass it:\n\n```ruby\n# Somewhere you have this function definition:\ndef naive_average(array)\n  array.sum / array.length\nend\n```\n\nThe test case, using RSpec:\n``` ruby\nrequire 'rspec'\n\nRSpec.describe \"#naive_average\" do\n  G = PropCheck::Generators\n\n  it \"returns an integer for any input\" do\n    PropCheck.forall(G.array(G.integer)) do |numbers|\n      result = naive_average(numbers)\n\n      expect(result).to be_a(Integer)\n    end\n  end\nend\n```\n\nThe test case, using MiniTest:\n``` ruby\nrequire 'minitest/autorun'\nclass NaiveAverageTest \u003c MiniTest::Unit::TestCase\n  G = PropCheck::Generators\n\n  def test_that_it_returns_an_integer_for_any_input()\n    PropCheck.forall(G.array(G.integer)) do |numbers|\n      result = naive_average(numbers)\n\n      assert_instance_of(Integer, result)\n    end\n  end\nend\n```\n\nThe test case, using test-unit:\n``` ruby\nrequire \"test-unit\"\n\nclass TestNaiveAverage \u003c Test::Unit::TestCase\n  G = PropCheck::Generators\n\n  def test_that_it_returns_an_integer_for_any_input\n    PropCheck.forall(G.array(G.integer)) do |numbers|\n      result = naive_average(numbers)\n\n      assert_instance_of(Integer, result)\n    end\n  end\nend\n```\n\nThe test case, using only vanilla Ruby:\n```ruby\n# And then in a test case:\nG = PropCheck::Generators\n\nPropCheck.forall(G.array(G.integer)) do |numbers|\n  result = naive_average(numbers)\n\n  raise \"Expected the average to be an integer!\" unless result.is_a?(Integer)\nend\n```\n\nWhen running this particular example PropCheck very quickly finds out that we have made a programming mistake:\n```ruby\nZeroDivisionError: \n(after 6 successful property test runs)\nFailed on: \n`{\n    :numbers =\u003e []\n}`\n\nException message:\n---\ndivided by 0\n---\n\n(shrinking impossible)\n---\n```\n\nClearly we forgot to handle the case of an empty array being passed to the function.\nThis is a good example of the kind of conceptual bugs that PropCheck (and property-based testing in general)\nare able to check for.\n\n\n#### Shrinking\n\nWhen a failure is found, PropCheck will re-run the block given to `forall` to test\n'smaller' inputs, in an attempt to give you a minimal counter-example,\nfrom which the problem can be easily understood.\n\nFor instance, when a failure happens with the input `x = 100`,\nPropCheck will see if the failure still happens with `x = 50`.\nIf it does , it will try `x = 25`. If not, it will try `x = 75`, and so on.\n\nThis means for example that if something only goes for wrong for `x \u003e= 8`, the program will try:\n- `x = 100`(fails),\n- `x = 50`(fails), \n- `x = 25`(fails), \n- `x = 12`(fails), \n- `x = 6`(succeeds), `x = 9` (fails)\n- `x = 7`(succeeds), `x = 8` (fails).\n\nand thus the simplified case of `x = 8` is shown in the output.\n\nThe documentation of the provided generators explain how they shrink.\nA short summary:\n- Integers shrink to numbers closer to zero.\n- Negative integers also attempt their positive alternative.\n- Floats shrink similarly to integers.\n- Arrays and hashes shrink to fewer elements, as well as shrinking their elements.\n- Strings shrink to shorter strings, as well as characters earlier in their alphabet.\n\n### Builtin Generators\n\nPropCheck comes with [many builtin generators in the PropCheck::Generators](https://www.rubydoc.info/github/Qqwy/ruby-prop_check/main/PropCheck/Generators) module.\n\nIt contains generators for:\n- (any, positive, negative, etc.) integers, \n- (any, only real-valued) floats, \n- (any, printable only, alphanumeric only, etc) strings and symbols\n- fixed-size arrays and hashes \n- as well as varying-size arrays, hashes and sets.\n- dates, times, datetimes.\n- and many more!\n\nIt is common and recommended to set up a module alias by using `G = PropCheck::Generators` in e.g. your testing-suite files to be able to refer to all of them.\n_(Earlier versions of the library recommended including the module instead. But this will make it very simple to accidentally shadow a generator with a local variable named `float` or `array` and similar.)_\n\n### Writing Custom Generators\n\nAs described in the previous section, PropCheck already comes bundled with a bunch of common generators.\n\nHowever, you can easily adapt them to generate your own datatypes:\n\n#### Generators#constant / Generator#wrap\n\nAlways returns the given value. No shrinking.\n\n#### Generator#map\n\nAllows you to take the result of one generator and transform it into something else.\n    \n    \u003e\u003e G.choose(32..128).map(\u0026:chr).sample(1, size: 10, rng: Random.new(42))\n    =\u003e [\"S\"]\n\n#### Generator#bind\n\nAllows you to create one or another generator conditionally on the output of another generator.\n\n    \u003e\u003e G.integer.bind { |a| G.integer.bind { |b| G.constant([a , b]) } }.sample(1, size: 100, rng: Random.new(42)\n    =\u003e [[2, 79]]\n\nThis is an advanced feature. Often, you can use a combination of `Generators.tuple` and `Generator#map` instead:\n\n    \u003e\u003e G.tuple(G.integer, G.integer).sample(1, size: 100, rng: Random.new(42))\n    =\u003e [[2, 79]]\n\n#### Generators.one_of\n\nUseful if you want to be able to generate a value to be one of multiple possibilities:\n\n    \n    \u003e\u003e G.one_of(G.constant(true), G.constant(false)).sample(5, size: 10, rng: Random.new(42))\n    =\u003e [true, false, true, true, true]\n\n(Note that for this example, you can also use `G.boolean`. The example happens to show how it is implemented under the hood.)\n\n#### Generators.frequency\n\nIf `one_of` does not give you enough flexibility because you want some results to be more common than others,\nyou can use `Generators.frequency` which takes a hash of (integer_frequency =\u003e generator) keypairs.\n\n    \u003e\u003e G.frequency(5 =\u003e G.integer, 1 =\u003e G.printable_ascii_char).sample(size: 10, rng: Random.new(42))\n    =\u003e [4, -3, 10, 8, 0, -7, 10, 1, \"E\", 10]\n\n#### Others\n\nThere are even more functions in the `Generator` class and the `Generators` module that you might want to use,\nalthough above are the most generally useful ones.\n\n[PropCheck::Generator documentation](https://www.rubydoc.info/github/Qqwy/ruby-prop_check/main/PropCheck/Generator)\n[PropCheck::Generators documentation](https://www.rubydoc.info/github/Qqwy/ruby-prop_check/main/PropCheck/Generators)\n\n\n## Usage within Rails / with a database\n\nUsing PropCheck for unit tests in a Rails, Sinatra, Hanami, etc. project is very easy.\nHere are some simple recommendations for the best results:\n- Tests that do not need to use the DB at all are usually 10x-100x faster. Faster tests means that you can configure PropCheck to do more test runs.\n- If you do need to use the database, use the [database_cleaner](https://github.com/DatabaseCleaner/database_cleaner) gem, preferibly with the fast `:transaction` strategy if your RDBMS supports it. To make sure the DB is cleaned around each generated example, you can write the following helper:\n``` ruby\n  # Version of PropCheck.forall\n  # which ensures records persisted to the DB in one generated example\n  # do not affect any other\n  def forall_with_db(*args, **kwargs, \u0026block)\n      PropCheck.forall(*args, **kwargs)\n               .before { DatabaseCleaner.start }\n               .after { DatabaseCleaner.clean }\n               .check(\u0026block)\n  end\n```\n- Other setup/cleanup should also usually happen around each generated example rather than around the whole test: Instead of using the hooks exposed by RSpec/MiniTest/test-unit/etc., use the before/after/around hooks exposed by PropCheck.\n\n## Development\n\nAfter checking out the repo, use the [just](https://github.com/casey/just) command runner for common tasks:\n\n- `just setup`: Installs dev dependencies\n- `just test`: Runs the test suite\n- `just console`: Opens an IRb console with the gem loaded for experimenting.\n- `just install`: Install the gem on your local machine.\n- `just release`: Create and push a new release to the git repo and Rubygems. (Be sure to increase the version number in `version.rb` first!)\n\n## Contributing\n\nBug reports and pull requests are welcome on GitHub at https://github.com/Qqwy/ruby-prop_check . This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.\n\n## License\n\nThe gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).\n\n## Code of Conduct\n\nEveryone interacting in the PropCheck project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/Qqwy/ruby-prop_check/blob/main/CODE_OF_CONDUCT.md).\n\n## Attribution and Thanks\n\nI want to thank the original creators of QuickCheck (Koen Claessen, John Hughes) as well as the authors of many great property testing libraries that I was/am able to use as inspiration.\nI also want to greatly thank Thomasz Kowal who made me excited about property based testing [with his great talk about stateful property testing](https://www.youtube.com/watch?v=q0wZzFUYCuM), \nas well as Fred Herbert for his great book [Property-Based Testing with PropEr, Erlang and Elixir](https://propertesting.com/) which is really worth the read (regardless of what language you are using).\n\nThe implementation and API of PropCheck takes a lot of inspiration from the following projects:\n\n- Haskell's [QuickCheck](https://hackage.haskell.org/package/QuickCheck) and [Hedgehog](https://hackage.haskell.org/package/hedgehog);\n- Erlang's [PropEr](https://hex.pm/packages/proper);\n- Elixir's [StreamData](https://hex.pm/packages/stream_data);\n- Python's [Hypothesis](https://hypothesis.works/).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FQqwy%2Fruby-prop_check","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FQqwy%2Fruby-prop_check","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FQqwy%2Fruby-prop_check/lists"}