2017-09-26 10 views
0

以下のRSpecテストを作成します。私はsubjectに数回呼びかけようとします。しかし、私は期待される結果を得ることができません。私はsubjectを3回呼びますか?だから、私は3つの本の記録を期待している。 subjectは一度も呼び出せませんか?RSpecで件名を何度も呼び出す方法

require 'rails_helper' 

RSpec.describe Book, type: :model do 
    context 'some context' do 
    subject { Book.create } 

    before do 
     subject 
    end 

    it 'something happen' do 
     subject 
     expect { subject }.to change{ Book.count }.from(0).to(3) 
    end 
    end 
end 

答えて

0

letsubjectmemoized (and lazy-loaded)あります。

あなたはこの

subject { 3.times { Book.create } } 

it 'something happen' do 
    expect { subject }.to change{ Book.count }.from(0).to(3) 
end 

それとも、(何らかの理由で)場合のようにそれを変更することができますが、3回何かを呼びたい - メソッドを定義します。

subject { create_book } 

def create_book 
    Book.create 
end 

before do 
    create_book 
end 

it 'something happen' do 
    create_book 
    expect { subject }.to change{ Book.count }.from(2).to(3) 
end 

そして、それが3回呼び出されます:ブロック前に1回、期待値の前に1回、期待値内に1回(ただし、変更は0からではなく、2からで、前に呼び出されたので2回目です)

関連する問題