Back to Course

Practice · SOLID · DIP · Card 1

Why is this class hard to test?

A small, focused class that does one thing. It has 12 lines of code and an unreasonable test setup. Why?

The code

A class that sends a Slack notification when a user signs up.

class NotifySignupToSlack
  def call(user)
    client = Slack::Notifier.new(ENV.fetch("SLACK_WEBHOOK_URL"))
    client.post(text: "New signup: #{user.email}")
  end
end

# The test:
test "posts to Slack" do
  ENV["SLACK_WEBHOOK_URL"] = "https://hooks.slack.com/services/..."
  stub_request(:post, "https://hooks.slack.com/...").to_return(status: 200)
  NotifySignupToSlack.new.call(users(:karim))
  assert_requested :post, "https://hooks.slack.com/..."
end

The question

Twelve lines of test for twelve lines of production code, and the test is more brittle than the code. What did the production class do that made the test this annoying?

Take a moment. A class that's easy to test is usually a class that doesn't hard-code what it depends on. What did this class hard-code, and how would the test look if it hadn't?