2
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 5 years have passed since last update.

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

Last updated at Posted at 2018-05-28

メモ

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

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