Testing

Crystal Unit Testing

Unit Testing

Crystal unit testing uses should for assertions.

Introduction to Crystal Unit Testing

Unit testing in Crystal ensures your code behaves as expected. Crystal's unit testing framework uses the should keyword to make assertions about your code. This guide will walk you through the basics of using should for testing in Crystal.

Setting Up a Crystal Project for Testing

Before you begin writing tests, ensure Crystal is installed on your system. Initialize a new Crystal project using the following command:

This command creates a new directory named my_project, complete with a basic project structure, including a spec directory for your tests.

Writing Your First Test

Let's write a simple test for a method that adds two numbers. Create a new file named spec/calculator_spec.cr and add the following code:

In this example, we define a Calculator class with an add method. The describe block contains our test case, which uses it to describe the behavior being tested. The should keyword makes an assertion that the result of calc.add(1, 2) should equal 3.

Running Your Tests

To run your tests, use the following command from your project's root directory:

This command will execute all the tests in your spec directory. If your tests pass, you'll see a confirmation message; otherwise, you'll receive details on any failures.

Advanced Assertions with Should

The should keyword is versatile and can be used for more complex assertions. Here are a few examples:

  • value.should be_a(String) - Asserts that value is a String.
  • list.should include(5) - Asserts that list contains the element 5.
  • result.should be_nil - Asserts that result is nil.

Conclusion

Crystal's unit testing framework, with its intuitive should assertions, provides a powerful way to ensure your code functions correctly. By integrating unit tests into your development process, you can catch errors early and build more reliable applications. Explore further to enhance your testing suite with more complex scenarios.

Previous
Testing