59
37

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 subjectの使い方

Posted at

rspecのsubjectは letなどと同じように、処理を変数に置き換えるものです。

spec.rb
let(:params) do
  {
    fuga: 'hoge'
  }
  
subject { get '/hogehoge', params: params; response }

このように subjectを定義することで、 get '/hogehoge', params: paramというリクエストをDRYに書くことが出来ます。

subjectがないとき.rb
context 'ログインしてるとき' do
  before { sign_in user }

  it do
    get '/hogehoge', params: params; response 
    expect(response).to have_http_status(:success)
  end
end

context 'ログインしてないとき' do
  before { sign_out user }

  it do
    get '/hogehoge', params: params; response 
    expect(response).to have_http_status(:redirect)
  end
end
subjectがあるとき.rb
subject { get '/hogehoge', params: params; response }

context ' ログインしてるとき' do
  before { sign_in user }
  it { is_expected.to have_http_status(:success)
end

context ' ログインしてないとき' do
  before { sign_out user }
  it { is_expected.to have_http_status(:redirect)
end

全体の行数が少なくなって、記述もDRYになって読みやすくなりました。

59
37
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
59
37

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?