tutorial rails mock ruby testing rspec

ruby - rails - RSpec: especificando múltiples llamadas a un método con diferentes argumentos cada vez



rspec rails 5 (1)

En rspec (1.2.9), ¿cuál es la forma correcta de especificar que un objeto recibirá múltiples llamadas a un método con un argumento diferente cada vez?

Lo pregunto debido a este resultado confuso:

describe Object do it "passes, as expected" do foo = mock(''foo'') foo.should_receive(:bar).once.ordered.with(1) foo.should_receive(:bar).once.ordered.with(2) foo.bar(1) foo.bar(2) end it "fails, as expected" do foo = mock(''foo'') foo.should_receive(:bar).once.ordered.with(1) # => Mock "foo" expected :bar with (1) once, but received it twice foo.should_receive(:bar).once.ordered.with(2) foo.bar(1) foo.bar(1) foo.bar(2) end it "fails, as expected" do foo = mock(''foo'') foo.should_receive(:bar).once.ordered.with(1) foo.should_receive(:bar).once.ordered.with(2) foo.bar(2) # => Mock "foo" received :bar out of order foo.bar(1) end it "fails, as expected, but with an unexpected message" do foo = mock(''foo'') foo.should_receive(:bar).once.ordered.with(1) foo.should_receive(:bar).once.ordered.with(2) foo.bar(1) foo.bar(999) # => Mock "foo" received :bar with unexpected arguments # => expected: (1) # => got (999) end end

Esperaba que el último mensaje de error fuera "esperado: (2)", no "esperado (1)". ¿He usado rspec incorrectamente?


Similar a esta question . La solución recomendada es llamar a as_null_object para evitar la confusión de mensajes. Asi que:

describe Object do it "fails, as expected, (using null object)" do foo = mock(''foo'').as_null_object foo.should_receive(:bar).once.ordered.with(1) foo.should_receive(:bar).once.ordered.with(2) foo.bar(1) foo.bar(999) # => Mock "foo" expected :bar with (2) once, but received it 0 times end end

El resultado no es el mismo que el de su segundo caso (es decir, "esperado 2 pero obtuvo 999"), pero muestra que la expectativa no se cumplió.