Everyday Rails - 7日目

9.スペックの高速化

  • subject, let, specify
  • shoulda-matchers
    • Gemfile の testグループに gem 'shoulda-matchers' を追加d
    • 書き方を書籍とちょっと変える
  • カスタムMatcerは使い方が難しそう
    • よほど重複しない限りは使わないほうが見通しが良さそう
  • spec/support/matchers/be_named.rb
RSpec::Matchers.define :be_named do |expected|
  match do |actual|
    actual.name.eql? expected
  end

  failure_message do |actual|
    "actual name '#{actual.name}'"
  end

  description do
    'return a full name as a string'
  end
end
  • spec/models/contact_spec.rb
describe Contact, type: :model do
  describe 'validate' do
    describe 'firstname' do
      # subject は不要
      # should は is_exptected.to で置き換え
      specify { is_expected.to validate_presence_of(:firstname) }
    end

    describe 'full name' do
      subject { create(:contact, firstname: 'John', lastname: 'Doe') }
      specify { expect(subject).to be_named 'John Doe' }
    end
  end
  # :
end
  • モック、スタブについては複数人開発(大規模開発?)や外部サービスを使っている場合を除いては使わないほうが良さそう
  • spec/models/contact_spec.rb
describe Contact, type: :model do
  # :
    describe 'GET #show' do
      let(:contact) do
        build_stubbed(:contact, firstname: 'Lawrence', lastname: 'Smith')
      end

      before do
        allow(contact).to receive(:persisted?).and_return(true)
        allow(Contact).to \
          receive(:order).with('lastname, firstname').and_return([contact])
        allow(Contact).to \
          receive(:find).with(contact.id.to_s).and_return(contact)
        allow(contact).to receive(:save).and_return(true)

        get :show, id: contact
      end

      it 'assigns the requested contact to @contact' do
        expect(assigns(:contact)).to eq contact
      end

      it 'renders the :new template' do
        expect(response).to render_template :show
      end
    end
  # : 
end
  • guard, spring
    • Gemfile の test グループに、 gem 'guard-rspec'、gem 'spring-commands-rspec' を追加
    • tagを使うことはなさそう

f:id:yossk:20141208105958j:plain

  • 不要なテストを削除することで高速化

今日の感想

モック、スタブについては使いどころに注意、か。