class Burger
attr_reader :meat, :cheese
def initialize(meat, cheese)
@meat = meat
@cheese = cheese
end
end
RSpec.describe "have_attributes matcher" do
describe Burger.new("Beef", "Cheddar")
it "checks attribute and value" do
expect(subject).to have_attributes(meat: "Beef")
expect(subject).to have_attributes(cheese: "Cheddar")
end
it { is_expected.to have_attributes(meat: "Beef") }
it { is_expected.to have_attributes(cheese: "Cheddar") }
end
end
RSpec.describe "include matcher" do
describe "yummy burger" do
it "checks substring" do
expect(subject).to include("yummy")
expect(subject).to include("burger")
expect(subject).to include("bur")
end
end
describe [1, 5, 7] do
it "checks inclusion value in the array" do
expect(subject).to include(1)
expect(subject).to include(5)
expect(subject).to include(7)
expect(subject).to include(7, 5)
end
end
describe { t: 5, y: 7} do
it "checks key or key value pair" do
expect(subject).to include(:t)
expect(subject).to include(:t, :y)
expect(subject).to include(t: 5)
end
it { is_expected.to include(:y)}
end
end
class Burger
def eat
p "yummy!!!!"
end
def discard
p "So bad..."
end
def buy(money)
p "i will spend #{money} to buy this good shit!!"
end
end
RSpec.describe "respond_to matcher" do
describe Burger do
it "checks an object respond method" do
expect(subject).to respond_to(:eat)
expect(subject).to respond_to(:eat, :discard)
expect(subject).to respond_to(:eat, :discard, :buy)
end
it "checks method and arguments" do
expect(subject).to respond_to(:buy).with(1).arguments
end
end
end
RSpec.describe "satisfy matcher" do
subject { 'level' }
it "is a palindrome" do
expect(subject).to satisfy { |value| value == value.reverse }
end
it "can do something in block" do
expect(10).to satisfy { |value| value / 2 == 5 }
end
it "can add custom message" do
expect(100).to satisfy("bigger than 50") do |value|
value > 50
end
end
end
他就是一個只要能夠在 block 裡面滿足條件,就可以通過測試的一個好東西!
彈性很高,可以在裡面寫入很多 Ruby 的語法,在測試的時候也比較不會綁手綁腳的。
客製化訊息也會在 Output 上一併出現,這個 Matcher 先推推!
compound expectation
這個就是一個 expectation 而且蠻無聊的,想說就也提一下好了!
簡單來說就是合成你的 RSpec 語法,要 and && 或是 or || 對比上你的複數 Matcher 才能夠通過~
compound expectation
ruby
1 2 3 4 5 6 7 8 9 10 11
RSpec.describe 30 do
it "test for multiple matchers" do
expect(subject).to be_even.and be > 25
end
describe [1, 5, 7] do
it "can use or" do
expect(subject.sample).to eq(1).or eq(5).or eq(7)
end
end
end