Skip to content

Subject and its example

Cyril Kato edited this page Nov 1, 2026 · 1 revision

subject is let(:subject); is_expected is expect { subject }, so what the subject raises can be expected too. its(:name, *arguments) sends name to the subject with the arguments when the matcher asks for it.

require "r_spec"

RSpec.describe Array do
  subject { [1, 2, 3] }

  it { is_expected.to eq [1, 2, 3] }
  it { is_expected.to be_an_instance_of described_class }

  its(:size) { is_expected.to be 3 }
  its(:first) { is_expected.to be 1 }
  its(:fetch, 9) { is_expected.to raise_exception IndexError }
  its(:sum, 10) { is_expected.to be 16 }
  its(:join, "-") { is_expected.to eq "1-2-3" }

  context "when inherited" do
    subject { super() + [4] }

    its(:size) { is_expected.to be 4 }
  end

  describe "without a subject" do
    subject { 42 / 0 }

    it { is_expected.to raise_exception ZeroDivisionError }
  end
end
$ ruby spec/subject_spec.rb
spec/subject_spec.rb:6: Success: expected [1, 2, 3] to eq [1, 2, 3]
spec/subject_spec.rb:7: Success: expected [1, 2, 3] to be an instance of Array
spec/subject_spec.rb:9: Success: expected 3 to be 3
spec/subject_spec.rb:10: Success: expected 1 to be 1
spec/subject_spec.rb:11: Success: expected #<IndexError: index 9 outside of array bounds: -3...3> to raise exception IndexError
spec/subject_spec.rb:12: Success: expected 16 to be 16
spec/subject_spec.rb:13: Success: expected "1-2-3" to eq "1-2-3"
spec/subject_spec.rb:18: Success: expected 4 to be 4
spec/subject_spec.rb:24: Success: expected #<ZeroDivisionError: divided by 0> to raise exception ZeroDivisionError

Clone this wiki locally