Search code examples
ruby-on-railsruby-on-rails-4testingrspecrspec-rails

Is it worth testing low-level code such as scopes?


Is it actually profitable to test "core" features such as scopes and sorting? I have several tests that test functionality similar to what's below. It seems to me that it's just testing Rails core features (scopes and sorting), which are probably very well-tested already.

I know this may seem like an "opinion" question, but what I'm trying to find out is if someone knows anything I would miss if I assume that scopes/sorting are already tested and not valuable for developers to test.

My thoughts are that even if scopes/sorting are "broken", there's nothing I can really do if the Rails core code is broken as I refuse to touch core code without a very, very good reason (makes updating later on a nightmare...).

I feel "safe" with more tests but if these tests aren't actually providing value, then they are just taking up space and time on the test suite.

# user.rb model
class User < ActiveRecord::Base
  scope :alphabetical, -> { order("UPPER(first_name), UPPER(last_name)") }
end

# user_spec.rb spec
context "scopes" do
  describe ".alphabetical" do
    it "sorts by first_name, last_name (A to Z)" do
      user_one = create(:user, first_name: "Albert", "Johnson")
      user_two = create(:user, first_name: "Bob", "Smith")
      ...

      expect(User.all.alphabetical.first.first_name).to eq("Albert")
    end
  end
end

Solution

  • Yes, you should test the scope. It's not all built-in functionality; you had to write it. It sorts on two criteria, so it needs two tests, one to prove that it sorts by first name (which your test above shows), and another to prove that it falls back on last name when the first names are the same.

    If the scope were simpler, you could skip unit-testing it if it was fully tested in an acceptance or higher-level unit test. But as soon as the scope itself needs more than one test, you should do that in tests of the scope itself, not in tests of higher-level code. If you tried to do it in tests of higher-level code it would be hard for readers to find where the details of the scope are tested, and it could lead to duplication if the tests of each caller tested all of the functionality of the scope.