DEV Community

Cover image for Explaining RSpec minimal code style rules in 2 minutes
Vasily Polovnyov
Vasily Polovnyov

Posted on

Explaining RSpec minimal code style rules in 2 minutes

Sometimes I meet code like this:

describe "callbacks" do
  describe "before validation" do
    let(:blog) {create(:blog) }
    context "when slug is not set" do
      it "generates it" do
        item = Post.new(blog: blog)
        item.validate
        expect(item.slug).not_to be_nil
      end
    end
    context "when slug is set" do
      it "does not change it" do
        item = Post.new({blog: blog })
        item.slug = 'in the darkness'
        item.validate
        expect(item.slug).to eq 'in the darkness'
      end
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

This is very hard to read. And oddities in formatting cause the eye to stumble.

To make the test a hundred times easier to read, stick to the basic rules of hygiene in tests: separate phases and rely on code style.

Separate phases

The test consists of three phases: setup, exercise, and verify. Separate them from each other with a blank line. Also separate the context/describe/it blocks:

describe "callbacks" do
  describe "before validation" do
    let(:blog) {create(:blog) }

    context "when slug is not set" do
      it "generates it" do
        item = Post.new(blog: blog)

        item.validate

        expect(item.slug).not_to be_nil
      end
    end

    context "when slug is set" do
      it "does not change it" do
        item = Post.new({blog: blog })
        item.slug = 'in the darkness'

        item.validate

        expect(item.slug).to eq 'in the darkness'
      end
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

Rely on code style

To write consistent code and not have to remember what quotes to use, add Rubocop. Then add Sublime-Linter and SublimeLinter-rubocop to see errors right in the editor:

Alt Text

And then it will be easier to read and understand the tests:

describe "callbacks" do
  describe "before validation" do
    let(:blog) { create(:blog) }

    context "when slug is not set" do
      it "generates it" do
        item = Post.new(blog: blog)

        item.validate

        expect(item.slug).not_to be_nil
      end
    end

    context "when slug is set" do
      it "does not change it" do
        item = Post.new(blog: blog)
        item.slug = "in the darkness"

        item.validate

        expect(item.slug).to eq "in the darkness"
      end
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

Top comments (0)