4
0

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にて引数が必要なsubjectの使い方

Posted at

はじめに

RSpecで、同じメソッドに対してのテストを複数回書くシーンでは、subjectを使うことでDRYなコードを書くことができます。
ここでは引数が必要なメソッドのテストをsubjectを用いて書きます。

実装

ユーザー名(user_name)、自己紹介(pr)カラムがあるユーザーを、フリーワードで検索するuser_search(free_word)メソッドをテストするとします。普通に書くと以下のように繰り返し同じ処理が出てきます。

spec/models/user_spec.rb
describe "#user_search" do
  context "when 'user_name1' is given" do
    it "return 1 result" do
      expect(Job.user_search("user_name1").count).to eq 1
    end
  end

  context "when 'pr1' is given" do
    it "return 1 result" do
      expect(Job.user_search("pr1").count).to eq 1
    end
  end
end

これは以下のようにsubjectでまとめて処理を書くことができます。

spec/models/user_spec.rb
describe "#user_search" do
  subject { User.user_search(field).count }

  context "when user_name1 is given" do
    let(:field) { "user_name1" }
    is_expected.to eq 1
  end

  context "when pr1 is given" do
    let(:field) { "pr1" }
    is_expected.to eq 1
  end
end

引数はletで定義することができます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?