Site icon R-bloggers

Mastering Test Driven Development: Build the Right Thing First

[This article was first published on jakub::sobolewski, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Writing test cases first helps us understand better what we need to build.

Tests allow us to express how the code should behave.

If we focus on asserting the behavior of code, we end up with tests that are also a functional documentation.

A business expert or other developer can read the tests and quickly understand what the code does, making it easier to correct any misunderstandings.

❌ Change your tests like these:

describe("validate", {
  it("should work correctly", {
    # Complex setup
    # Many expectations
  })
})

✅ To tests like these:

describe("validate", {
  it("should return TRUE if data passes validation", {
    # Arrange

    # Act

    # Assert

  })

  it("should return FALSE if data does not pass validation", {
    # ...
  })

  it("should throw an error if input is not a table", {
    # ...
  })
})

Before writing each test case, ask yourself:

Answering those questions:

And it all comes down to writing tests first. Build the right thing on the first try.

To leave a comment for the author, please follow the link and comment on their blog: jakub::sobolewski.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Exit mobile version