ruby - rails - ¿Hay alguna manera de resguardar un método de un módulo incluido con Rspec?
rspec tutorial (1)
Tenga en cuenta que no puede llamar directamente a M.foo
! Tu código solo parece funcionar porque te M.foo
de M.foo
para regresar :bar
.
Cuando abre A
metaclase ( class << self
) para incluir M
, tiene que simular cualquier instancia de M
, que se está agregando a su bloque before
:
allow_any_instance_of(M).to receive(:foo).and_return(:bar)
module M
def foo
:M
end
end
module A
class << self
include M
def foo
super
end
end
end
describe "trying to stub the included method" do
before do
allow(M).to receive(:foo).and_return(:bar)
allow_any_instance_of(M).to receive(:foo).and_return(:bar)
end
it "should be stubbed when calling M" do
expect(M.foo).to eq :bar
end
it "should be stubbed when calling A" do
expect(A.foo).to eq :bar
end
end
Tengo un módulo que está incluido en otro módulo, y ambos implementan el mismo método. Me gustaría resumir el método del módulo incluido, algo como esto:
module M
def foo
:M
end
end
module A
class << self
include M
def foo
super
end
end
end
describe "trying to stub the included method" do
before { allow(M).to receive(:foo).and_return(:bar) }
it "should be stubbed when calling M" do
expect(M.foo).to eq :bar
end
it "should be stubbed when calling A" do
expect(A.foo).to eq :bar
end
end
La primera prueba está pasando, pero la segunda muestra:
Failure/Error: expect(A.foo).to eq :bar
expected: :bar
got: :M
¿Por qué el talón no funciona en este caso? ¿Hay alguna manera diferente de lograr esto?
¡Gracias!
-------------------------------------ACTUALIZAR------------ ----------------------
¡Gracias! el uso de allow_any_instance_of (M) resolvió este. Mi siguiente pregunta es: ¿qué sucede si uso preceder y no incluir? vea el siguiente código:
module M
def foo
super
end
end
module A
class << self
prepend M
def foo
:A
end
end
end
describe "trying to stub the included method" do
before { allow_any_instance_of(M).to receive(:foo).and_return(:bar) }
it "should be stubbed when calling A" do
expect(A.foo).to eq :bar
end
end
Esta vez, el uso de allow_any_instance_of (M) da como resultado un bucle infinito. ¿porqué es eso?