質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

RSpec

RSpecはRuby用のBDD(behaviour-driven development)フレームワークです。

Q&A

2回答

3771閲覧

【RSpec】テストを関数のように再利用したい

a4308449

総合スコア6

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

RSpec

RSpecはRuby用のBDD(behaviour-driven development)フレームワークです。

0グッド

0クリップ

投稿2014/10/03 01:45

RSpecで他のテストで作ったテストを簡単に再利用する方法はありますか?

イメージ

lang

1 describe "テスト1" do 2 3 it "テスト1-1" 4 5 it "テスト1-2" 6 7 end 8 9 10 describe "テスト2" do 11 12 it "テスト1-1" ←"テスト1"で作ったテストと同じ物を実行したい 13 14 end 15 16 describe "テスト3" do 17 18 it "テスト3-1" 19 20 it "テスト1" ←"テスト1"をそのまま実行したい 21 22 end

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

TaMaMhyu さんが書いておられますが shared_example でいけますね。

RSpec の入門とその一歩先へ、第2イテレーション ~RSpec 3バージョン~ - Qiita
の例を引用すると

describe MessageFilter, 'with argument "foo"' do subject { MessageFilter.new('foo') } it { is_expected.to be_detect('hello from foo') } it { is_expected.not_to be_detect('hello, world') } end describe MessageFilter, 'with argument "foo","bar"' do subject { MessageFilter.new('foo', 'bar') } it { is_expected.to be_detect('hello from bar') } it { is_expected.to be_detect('hello from foo') } it { is_expected.not_to be_detect('hello, world') } end

では

it { is_expected.to be_detect('hello from foo') } it { is_expected.not_to be_detect('hello, world') }

が重複しています(というかコピペしただけです)。
これを

shared_examples 'MessageFilter with argument "foo"' do it { is_expected.to be_detect('hello from foo') } it { is_expected.not_to be_detect('hello, world!') } end describe MessageFilter, 'with argument "foo"' do subject { MessageFilter.new('foo') } it_behaves_like 'MessageFilter with argument "foo"' end describe MessageFilter, 'with argument "foo","bar"' do subject { MessageFilter.new('foo', 'bar') } it { is_expected.to be_detect('hello from bar') } it_behaves_like 'MessageFilter with argument "foo"' end

のように shared_examples で括り出します。
括り出した部分は it_behaves_like で指定します。

it_behaves_like の引数は十分に説明的で、先にある shared_examples の中身を見にいかなくても済むことが望ましいと考えています。以上が、私が shared_examples でかなり長い名前をつけた理由です。

とあるように、 shared_examples ではできるだけ分かりやすい名前を付けるべき。

RSpecの入門とその一歩先へ ~RSpec 3バージョン~ - Qiita の記事を一通り(3つに分かれています)読まれることを強くお勧めします。

投稿2014/10/03 04:40

riocampos

総合スコア241

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

shared_exampleというのを使えばできそうです。

投稿2014/10/03 01:59

TaMaMhyu

総合スコア1356

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問