Help us understand the problem. What is going on with this article?

RSpec でメソッド呼び出しの引数をブロックでチェック

RSpec の expect(foo).to receive(:bar).with(...) では引数のチェックがいくつかの方法で可能だが、ブロックで検証したいケースが結構ある。

with には matcher を渡すことができるので、カスタム matcher を定義してやればよい。
下記の例では Struct の特定の attribute のみ検証している

RSpec::Matchers.define :a_valid_argument do
  match {|actual| block_arg.call(actual) }
end

it "should call with valid argument" do
  jon = Struct.new(:name).new("Jon")

  expect($stdout).to receive(:write).with(
    a_valid_argument {|a| a.name == "Jon" },
  )

  $stdout.write(jon)
end

なお、with による引数の検証は引数ごとに行われるので複数の引数をとるメソッドの場合は、引数ごとに matcher を渡す必要がある。

it "should call with valid arguments" do
  jon = Struct.new(:name).new("Jon")
  dany = Struct.new(:name).new("Dany")

  expect($stdout).to receive(:write).with(
    a_valid_argument {|a| a.name == "Jon" },
    a_valid_argument {|a| a.name == "Dany" },
  )

  $stdout.write(jon, dany)
end
labocho
普通の Web プログラマ
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした