RSpec Mocks provides ordered since at least RSpec 3.0:
You can use ordered to limit the waiting order of multiple messages. This is usually not recommended, because in most cases the order does not matter, and using the order should make your spec fragile, but it is useful from time to time. When you use ordered, an example will be transmitted only if messages are received in the declared order.
Please note that RSpec agrees with @spickermann that this is not recommended. However, there are some cases where this is necessary, especially when working with legacy code.
Here is an example RSpec transfer:
RSpec.describe "Constraining order" do it "passes when the messages are received in declared order" do collaborator_1 = double("Collaborator 1") collaborator_2 = double("Collaborator 2") expect(collaborator_1).to receive(:step_1).ordered expect(collaborator_2).to receive(:step_2).ordered expect(collaborator_1).to receive(:step_3).ordered collaborator_1.step_1 collaborator_2.step_2 collaborator_1.step_3 end end
And unsuccessful examples:
RSpec.describe "Constraining order" do it "fails when messages are received out of order on one collaborator" do collaborator_1 = double("Collaborator 1") expect(collaborator_1).to receive(:step_1).ordered expect(collaborator_1).to receive(:step_2).ordered collaborator_1.step_2 collaborator_1.step_1 end it "fails when messages are received out of order between collaborators" do collaborator_1 = double("Collaborator 1") collaborator_2 = double("Collaborator 2") expect(collaborator_1).to receive(:step_1).ordered expect(collaborator_2).to receive(:step_2).ordered collaborator_2.step_2 collaborator_1.step_1 end end
source share