Upgrade to Pro — share decks privately, control downloads, hide ads and more …

RSpec -基本の基-

yuki21
August 21, 2020

RSpec -基本の基-

5分間社内LT資料

yuki21

August 21, 2020
Tweet

More Decks by yuki21

Other Decks in Programming

Transcript

  1. 基本構⽂ # user_spec.rb RSpec.describe User, type: :model do describe "validations"

    do it "name: nil is expected not to be valid" do user = build(:user, name: nil) expect(user).to_not be_valid end end describe "methods" do ... end end ※ 補⾜ describeは「説明する」、expectは「期待する」という意味です。 また、it =example には単⼀のテストを記述します。
  2. 実⾏結果 User validations name: nil is expected not to be

    valid Finished in 0.28044 seconds (files took 2.4 seconds to load) 1 example, 0 failures
  3. Context 条件でグルーピングする際はdescribeではなくcontextを使います。 describe "methods" do context "before confirm" do it

    "active is expected to be false" do user = build(:user) expect(user.active?).to be false end end context "after confirm" do it "active is expected to be true" do user = build(:user, :confirmed) expect(user.active?).to be true end end end
  4. 実⾏結果 User methods before confirm active is expected to be

    false after confirm active is expected to be true Finished in 0.24582 seconds (files took 1.39 seconds to load) 2 examples, 0 failures
  5. before 共通の処理をbeforeでまとめることができます。 RSpec.describe User, type: :model do before do @user

    = build(:user) end describe "validations" do ... end describe "methods" do ... end end
  6. let beforeはletで置き換えが可能です。 RSpec.describe User, type: :model do let do user

    = build(:user) end let(:user) { build(:user) } describe "validations" do it "name: nil is expected not to be valid" do expect(user).to_not be_valid end end end beforeと違う点は、letは遅延評価されるという点です。
  7. subject subjectを利⽤することで、テスト対象をまとめることができます。 describe "#active?" do subject { user.active? } context

    "before confirm" do let(:user) { build(:user) } it { is_expected.to be false } end context "after confirm" do let(:user) { build(:user, :confirmed) } it { is_expected.to be true } end end
  8. shoulda-matchers describe "validations" do let(:user) { create(:user) } subject {

    user } it { is_expected.to belong_to(:company) } it { is_expected.to have_many(:restaurants).through(:company) } it { is_expected.to have_secure_password } it { is_expected.to_not allow_value(nil).for(:name) } it { is_expected.to_not allow_value(nil).for(:password) } it { is_expected.to_not allow_value(nil).for(:mail_address) } it { is_expected.to validate_length_of(:zipcode1).is_at_most(3) } it { is_expected.to validate_length_of(:zipcode2).is_at_most(4) } it { is_expected.to validate_numericality_of(:zipcode1).only_integer } it { is_expected.to validate_numericality_of(:zipcode2).only_integer } end