Rails: Testing named scopes with RSpec

后端 未结 4 1202
滥情空心
滥情空心 2020-12-24 05:40

I am new to testing Rails web applications and RSpec. I work with legacy code and need to add tests. So what is the best way to test finders and named scopes with RSpec?

相关标签:
4条回答
  • 2020-12-24 06:18

    From https://coderwall.com/p/hc8ofa/testing-rails-model-default_scope-with-rspec

    • no database queries
    • no need to represent the query in a structure

    Example:

    class Trip < ActiveRecord::Base
      default_scope { order(departure: :asc) }
      ...
    end
    
    RSpec.describe Trip, type: :model do
      it "applies a default scope to collections by departure ascending" do
        expect(Trip.all.to_sql).to eq Trip.all.order(departure: :asc).to_sql
      end
    end
    
    0 讨论(0)
  • 2020-12-24 06:25

    David Chelimsky testing scopes (updated)

    David Chelimsky example, (linked by Sam Peacey's comment), modernised.

    # app/models/user.rb
    
    class User < ActiveRecord::Base
      scope :admins, -> { where(admin: true) }
    end
    
    # spec/models/user_spec.rb
    
    RSpec.describe User, type: :model do
      describe ".admins" do
        it "includes users with admin flag" do
          admin = User.create!(admin: true)
          expect(User.admins).to include(admin)
        end
    
        it "excludes users without admin flag" do
          non_admin = User.create(admin: false)
          expect(User.admins).not_to include(non_admin)
        end
      end
    end
    

    This produces a more 'spec-like' output (when using --format documentation):

    User
      .admins
        includes users with admin flag
        excludes users without admin flag
    

    Note about origination of this answer:

    David Chelimsky, one of RSpec's creators, answered this question and Sam Peacey's link to it has more votes than the actual answer. The answer is not easy to find and follow as he is replying to someone and editing their answer in an email chain. This answer cleans that up and updates the RSpec code as, I guess, he would have written it today.

    0 讨论(0)
  • 2020-12-24 06:27

    The creator of RSpec has recently blogged he thinks Validations are behavior, associations are structure. In other words he finds that associations (and scopes) should not nessesarily be tested directly. Tests for these will follow from the behavior you want.

    In other words, current wisdom is that there is no need to test each scope directly, since you will cover these associations by testing the behavior of your application.

    0 讨论(0)
  • 2020-12-24 06:45

    The problem with the first approach is that it actually queries the database. It is slow and unnecessary. If you don't mind, you can safely use the first approach. The second approach is fast and clear so I would recommend it.

    0 讨论(0)
提交回复
热议问题