0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Rspec】before / let / let!

Posted at

##環境
Ruby 3.0.2
Rails 6.1.4.1

##before
describeやcontextの内部に書いたテストを実行するたびに毎回実行されるため、使う必要のないデータを作成してテストを遅くする原因になることがある

spec/models/article_spec.rb
describe "文字列に一致する記事を検索する" do
    before do
      @article1 = create(:article, title: "first")
      @article2 = create(:article, title: "second")
      @article3 = create(:article, title: "first article")
    end

    context "一致する記事が見つかるとき" do
      it "検索文字列に一致する記事を返すこと" do
        expect(Article.search(title: "first")).to include(@article1, @article3)
        expect(Article.search(title: "first")).to_not include(@article2)
      end
    end
end

##let
letは呼ばれたときに初めてデータを読み込む、遅延読み込みを実現するメソッド

letを使うメリットは下記の記事がわかりやすい

spec/models/article_spec.rb
describe "文字列に一致する記事を検索する" do
    let(:article1) { create(:article, title: "first") }
    let(:article2) { create(:article, title: "second") }
    let(:article3) { create(:article, title: "first article") }

    context "一致する記事が見つかるとき" do
      it "検索文字列に一致する記事を返すこと" do
        expect(Article.search(title: "first")).to include(article1, article3)
        expect(Article.search(title: "first")).to_not include(article2)
      end
    end
end

##let!
letとは異なり、let!は遅延読み込みされずすぐ実行されるためデータがすぐ作成される

spec/models/article_spec.rb
describe "文字列に一致する記事を検索する" do
    let!(:article1) { create(:article, title: "first") }
    let!(:article2) { create(:article, title: "second") }
    let!(:article3) { create(:article, title: "first article") }

    context "一致する記事が見つかるとき" do
      it "検索文字列に一致する記事を返すこと" do
        expect(Article.search(title: "first")).to include(article1, article3)
        expect(Article.search(title: "first")).to_not include(article2)
      end
    end

    context "一致する記事が見つからないとき" do
      it "空のコレクションを返すこと" do
        expect(Article.search(title: "third")).to be_empty
        expect(Article.count).to eq 3
      end
    end
end

##参考

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?