1
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

updated at

【Rspec】メソッドスタブ(allow ..to receive)の小さなサンプルメモ

メモ

person.rb
class Person
  def sex
    "man"
  end
  def test(test)
    ""
  end

  def test2(a1, a2)
    ""
  end
end
person_spec.rb
require 'person'

RSpec.describe Person do

  it {
    person = Person.new

    allow(person).to receive(:sex).and_return("woman")
    expect(person.sex).to eq("woman")

    allow(person).to receive(:sex) { "kure" }
    expect(person.sex).to eq("kure")

    allow(person).to receive(:test2) do |a1, a2|
      a1 + a2
    end
    expect(person.test2("1", "2")).to eq("12")


    allow(person).to receive(:test).with("hoge") do
      "hoge"
    end
    expect(person.test("hoge")).to eq("hoge")
  }

end
実行
 % rspec spec/person_spec_stub.rb
.

Finished in 0.02673 seconds (files took 0.24371 seconds to load)
1 example, 0 failures

参考

Method stubs - RSpec Mocks - RSpec - Relish https://relishapp.com/rspec/rspec-mocks/v/2-99/docs/method-stubs

13 method stubを使おう | RSpec入門 - プログラミングならドットインストール https://dotinstall.com/lessons/basic_rspec/27913

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
1
Help us understand the problem. What are the problem?