LoginSignup
21
19

More than 5 years have passed since last update.

ActiveRecordのscopeの簡単なテストを書くときのメモ

Last updated at Posted at 2014-04-10

scopeのテストを書くときどのレベルまで書くか迷いますが、ひとまずこれだけは書いときたい一番簡単なテストの書き方のメモ

ActiveRecrod::QueryMethodsにはxxx_valuesというattributeが用意されている。
これを利用する。

class Hoge < ActiveRecord::Base
  scope :target, -> {
    group(:kind, :flag).
    order(created_at: :desc)
  }
end

describe Hoge do
  describe 'scopes' do
    describe 'target' do
      subject { Hoge.target }
      its(:group_values) { should =~ [:kind, :flag] }
      its(:order_values) { should =~ [{created_at: :desc}] }
    end
  end
end

まだ検証しきれていませんが、where_values等の場合Arelが返されたりする。

class Hoge < ActiveRecord::Base
  scope :fuga, -> (a) { where(a: a) }
end

Hoge.fuga(10).where_values #=> [#<Arel::Nodes::Equality:0x007ffbcb89e378 @left=#<struct Arel::Attributes::Attribute relation=#<Arel::Table:0x007ffbcb03bfa0 @name="hoges", @engine=Hoge(no database connection), @columns=nil, @aliases=[], @table_alias=nil, @primary_key=nil>, name="a">, @right=10>]
21
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
19