RSpec: ¿Cadenas con argumentos?


Solo me pregunto si/cómo se pueden pasar los argumentos en las cadenas stub de rspec. Para dar un ejemplo, supongamos que tengo la siguiente acción:

def index
  @payments = Payment.order(:updated_at).where(:paid => true)
  @bad_payments = Payment.order(:some_other_field).where(:paid => false)
end

En mi especificación de controlador, me gustaría ser capaz de stub fuera de ambos métodos y devolver diferentes resultados. Si solo el campo @payments estuviera en la acción, usaría algo como

Payment.stub_chain(:order, :where) { return_this }

Pero por supuesto, eso devolverá el mismo valor para @bad_payments.

Así que, en resumen, ¿cómo incluyo las :updated_at y :paid => true como condiciones del talón?

Author: zishe, 2011-11-04

3 answers

Puedes usar esto:

Payment.stub_chain(:order, :where).with(:updated_at).with(:paid => true) { return_this }
 23
Author: Elad Maimon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-10 09:50:44

Puede usar el bloque stub anidado. El bloque puede aceptar argumentos, y el valor devuelto se utiliza como valor devuelto por la función.

Utilizo tap porque stub no devuelve el destinatario. El mock creado por double se devuelve como el resultado de method order, que where method es stub nuevamente.

Payment.stub(:order) { |order|
  double('ordered_payments').tap { |proxy|
    proxy.stub(:where) { |where|
      [order, where]
    }
  }
}

Payment.order(:updated_at).where(:paid => true)
# => returns [:updated_at, {:paid => true}]
 15
Author: Ian Yang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-15 15:03:46

Con rspec > 3 use esta sintaxis:

expect(Converter).to receive_message_chain("new.update_value").with('test').with(no_args)

En Lugar de stub_chain.

Lea más sobre cadenas de mensajes en la documentación. Y aquí está la documentación del argumento matchers.

 13
Author: czerasz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-23 17:13:47