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

Rspecのエラー: undefined method `include' for an instance of RSpec::Expectations::ValueExpectationTarget

Posted at

非常に初歩的なミスだが、戒めのための備忘録

Userモデルのfirst_nameにはvalidates :first_name, presence: trueというバリデーションがかけられており、バリデーションが正しく動いているかテストしたかったので、バリデーションをかけた際に以下のようにオブジェクトにエラーメッセージが含まれるか確認するための非常によくあるテストを書いた

it "is invalid without a first name" do
  user = User.new(
    first_name: nil,
    last_name: "Sumner",
    email: "tester@example.com",
    password: "dottle-nouveau-pavilion-tights-furze"
  )
  
  expect(user.errors[:first_name]).to include("can't be blank")
end

上記のspceを実行したところ以下のようなエラーが出た

1) User is invalid without a first name
     Failure/Error: expect(user.errors[:first_name]).include("can't be blank")

     NoMethodError:
       undefined method `include' for an instance of RSpec::Expectations::ValueExpectationTarget
     # ./spec/models/user_spec.rb:23:in `block (2 levels) in <top (required)>'

Rspec上で作成されたインスタンスにincludeメソッド(マッチャ)が無いなんてことあるか?と思ったが、単純にバリデーションを実行した結果を返すvalid?を書き忘れていたという超初歩的なミスだった

it "is invalid without a first name" do
  user = User.new(
    first_name: nil,
    last_name: "Sumner",
    email: "tester@example.com",
    password: "dottle-nouveau-pavilion-tights-furze"
  )

  user.valid? # 追加
  expect(user.errors[:first_name]).to include("can't be blank")
end

以上

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