RSpec هي أداة اختبار قائمة على التطوير الموجه بالسلوك (BDD) للغة Ruby.
هيكل المواصفات الأساسي (Spec Structure)
RSpec.describe Calculator do
let(:calculator) { Calculator.new }
describe "#add" do
context "when adding positive numbers" do
it "returns the arithmetic sum" do
expect(calculator.add(2, 3)).to eq(5)
end
end
context "when given invalid input" do
it "raises an ArgumentError" do
expect { calculator.add(2, "x") }.to raise_error(ArgumentError)
end
end
end
end
أهم المطابقات (Core Matchers)
# المساواة والقيمة
expect(actual).to eq(expected) # مساواة القيمة (==)
expect(actual).to be(expected) # تطابق الكائن (equal?)
# الصحة والقيم المنطقية
expect(actual).to be_truthy
expect(actual).to be_nil
expect(user).to be_active # يستدعي user.active?
# المجموعات والمصفوفات
expect(list).to include("ruby")
expect(list).to match_array([1, 2]) # نفس العناصر بصرف النظر عن الترتيب
expect(list).to be_empty
# المقارنات
expect(value).to be > 10
expect(value).to be_between(1, 100).inclusive
# الأخطاء والاستثناءات
expect { risky_call }.to raise_error(StandardError, /message/)
expect { safe_call }.not_to raise_error
الكائنات الوهمية والبدائل (rspec-mocks)
# حجب الدوال وتثبيت القيم (Stubbing)
allow(user).to receive(:name).and_return("Alice")
# توقع استدعاء الدالة
expect(notifier).to receive(:send_email).with("[email protected]").once
# كائن وهمي (Mock Double)
mock_service = double("PaymentService", charge: true)