[].all?
— вызов .all?
на пустом массиве вернет true (логично, подробнее)
rspec subject
— на этой неделе я научился в полной мере ценить возможности subject
в тестах rspec. При написании кода, рефакторинге и перемещении тестов нам нужно было обновлять тесты по ходу работы; subject
и let
сделали все это мечтой.
Представьте, что есть такой код:
require 'rspec' require 'ground_conditions' describe GroundConditions do describe "#is_wet" do subject { described_class.new(weather).is_wet } context "when it is raining" do let(:weather) { :rain } it { is_expected.to be true } end context "when the is snowing" do let(:weather) { :snow } it { is_expected.to be true } end context "when it is sunny" do let(:weather) { :sunny } it { is_expected.to be false} end end end class GroundConditions def initialize(weather) @weather = weather end def is_wet [:rain, :snow].include?(@weather) end end
Новый let
создается каждый раз, когда weather
необходимо изменить, но тема всегда остается неизменной. (Подробнее о let
)
Теперь предположим, что мы хотим превратить функцию is_wet
в функцию класса. Итак, он преобразуется в это:
class GroundConditions def self.is_wet(weather) [:rain, :snow].include?(weather) end end
Единственное, что нужно обновить в тестах, это subject
.
require 'rspec' require 'ground_conditions' describe GroundConditions do describe "#is_wet" do subject { described_class.is_wet(weather) } context "when it is raining" do let(:weather) { :rain } it { is_expected.to be true } end context "when the is snowing" do let(:weather) { :snow } it { is_expected.to be true } end context "when it is sunny" do let(:weather) { :sunny } it { is_expected.to be false} end end end