33
22

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 1 year has passed since last update.

Rspec で クラスメソッドのスタブを作る方法

Last updated at Posted at 2015-11-20

allow を使って、どんなクラスのメソッドでも書き換えられる。

例) モデルの定義

models/example.rb
class Example
  def self.class_method
    'This is real class method'
  end
end

スタブの作り方

  • allow でクラス名を指定する。
  • receive でメソッドを指定する。
  • and_returnでメソッド実行時の戻り値を指定する。
spec/test_spec.rb
require 'spec_helper'

describe do
  before do
    allow(Example).to receive(:class_method).and_return('This is stub class method')
  end

  it do
    p Example.class_method
  end
end

結果

"This is stub class method" が出力される。

環境

  • rspec-rails 2.14.1

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

メンター受付

33
22
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
33
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?