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

More than 1 year has passed since last update.

stubとmock(railsの場合)

Last updated at Posted at 2023-07-07

stub

スタブを使用することで、外部の依存関係を置き換えられる。
以下の例では、Nanoid.generateを置き換えて、abc123を返すようにした。

describe '#set_unique_id' do
  let(:foo) { build(:foo) }

  it 'sets the unique id using nanoid' do
    allow(Nanoid).to receive(:generate).and_return('abc123')

    foo.set_unique_id

    expect(foo.unique_id).to eq('abc123')
  end
end

mock

describe '#send_welcome_email' do
  let(:user) { create(:user) }

  it 'sends a welcome email' do
    mailer = double('UserMailer')
    expect(mailer).to have_received(:welcome_email).with(user).and_return(double(deliver_now: true))
    expect(UserMailer).to have_received(:with).with(user: user).and_return(mailer)

    user.send_welcome_email
  end
end
0
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
0
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?