LoginSignup
35

More than 5 years have passed since last update.

Rspecでmodelのスコープをテストするとき

Last updated at Posted at 2016-04-14

Rspecでcontroller,model,viewのテストをするとき、type: modeltype: requestすると使えるメソッドが違ってくる。
今回はmodelに定義したscopeをテストする方法。
定義したスコープは以下の通り。


  scope :open, -> {
    now = Time.current
    where("released_at <= ? AND (? < expired_at OR " +
      "expired_at IS NULL)", now, now) }

RSpecでテストすることを記述する


RSpec.describe Info, type: :model do
end

describeで枠を作る


RSpec.describe Info, type: :model do
 describe "scope" do
 end
end

describeでさらに枠を作る


RSpec.describe Info, type: :model do
 describe "scope" do
   describe "open" do
   end
 end
end

let!でRspec内のインスタンス変数を定義する


let!(Rspec内のインスタンス変数名) { create(:member, 属性名: , 属性名: )}
#create(:member)でFactoryGirlでテストデータを作成

  describe "scope" do
    describe "open" do
        let!(:applicable_article) { create(:article, released_at: Date.today, expired_at: Date.today+1) }
    end
  end
end

subject { Airticle.open }でAirticleモデルからopenスコープでインスタンスを取り出す。


  describe "scope" do
    describe "open" do
        let!(:applicable_article) { create(:article, released_at: Date.today, expired_at: Date.today+1) }
        subject { Article.open }
    end
  end
end

it{ is_expected.to include インスタンス変数名}
でテストする。is_expected.to includeArticle.openにインスタンス変数が含まれているかテストできる


describe "scope" do
    describe "open" do
        let!(:applicable_article) { create(:article, released_at: Date.today, expired_at: Date.today+1) }
        subject { Article.open }
        it { is_expected.to include applecable_article }
    end
  end
end

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
35