Write unit test with rspec in Rails (P1)

Tram Ho

Part 1: Introduction to test double and usage in RSpec

What is a test double?

Test Double is a general term for any situation where you replace an object that is actually used for testing purposes.

The main purpose of test double is to reduce dependencies and increase the independence of test cases. This is extremely important in unit test because we all want the test case to run as fast, independent and as less dependent on other “units” as possible.

Martin Fowler defines a double test as five different types, depending on the intended use:

  • Dummy : objects that are passed in but never actually used. Usually they are only used to fill a parameter list.
  • Fake : objects actually have the active implementation, but are not stored as in practice ( InMemoryTestDatabase is a prime example).
  • Stubs : objects that contain predefined data and use it to return data when calling to certain methods.
  • Spies : objects that record how it behaves like the number of times it was called, parameters received, etc.
  • Mocks : Just like stub can return the given data, but it is required to verify action called in test case.

Dummy

Usually used to fill a function’s parameters in cases where that parameter is not used to speed up test cases.

An example in Rspec:

Fake

Less commonly used in unit tests, however you can learn more about InMemoryTestDatabase here.

Stubs

Use to fake the return result of a function that you don’t really want to run that function. In rails I often use to stub unnecessary callback models in the test case, especially callbacks that affect the database or elasticsearch …

Rspec provides the following syntax for the stub method of an object:

Or you can use the following abbreviation:

An example of stub usage in Rspec:

Spies

Use to verify the actions in the method such as logging, firing noti, … We can verify the method is called several times, with any parameters, … Syntax to use spy in Rspec:

An example of using spies in Rspec:

Mock

As far as I can see, the mock is quite similar to stub + spies combined. Syntax of using mock in Rspec:

An example of using mock in rspec:

References

https://jmauerhan.wordpress.com/2018/10/04/the-5-types-of-test-doubles-and-how-to-create-them-in-phpunit/

https://www.martinfowler.com/articles/mocksArentStubs.html

https://martinfowler.com/bliki/TestDouble.html

https://rubydoc.info/gems/rspec-mocks/frames

https://blog.pragmatists.com/test-doubles-fakes-mocks-and-stubs-1a7491dfa3da

Share the news now

Source : Viblo