shouda runs setup many times #55

boriscy opened this Issue Sep 9, 2009 · 3 comments


None yet
3 participants

boriscy commented Sep 9, 2009

Shoulda runs setup many times Iam using using nested_attributes in Rails. It runs the setup for each should test.

require 'test_helper'
require 'mocha'

# En este caso no utilizamos el test por defecto de Rails
# sino que usamos una gem llamada shoulda, para poder ver la configuracion
# deben ir a: config/environments/test.rb

class InventarioTest < Test::Unit::TestCase
  should_belong_to :almacen
  should_have_many :inventario_detalles

  should_validate_presence_of :almacen_id

  context "Creacion" do
    setup do
      @fecha =

      @inventario = => 'Prueba', :tipo => 'ingreso', :almacen_id => 1)
      @inventario.inventario_detalles_attributes = [ {:item_id => 1, :cantidad => 2, :precio_unitario => 1.5},
            {:item_id => 2, :cantidad => 1, :precio_unitario => 1}]!
      # This line will print for each should test there is, in this case 2 times
      puts "Stock Creation: #{Stock.find_by_item_id_and_almacen_id(1,1).valor_inventario}"

    should "debe tener fecha" do
      assert_equal @fecha, @inventario.fecha
      puts "test fecha"

    should "have 2 items" do
      assert_equal 2, @inventario.inventario_detalles.size
      puts "test items"


ghost commented Sep 9, 2009

This is what is supposed to happen. The setup and teardown gets run before and after each test so they run in isolation, without side effects from other tests.

boriscy commented Sep 9, 2009

Thanx, I hava tested it and you are right, I would like to make it possible not to repeat each time the setup, because I want to first create, then edit, and delete, and this Model affects other model when chages are made.

If you have dependencies between tests, it's best to nest the context blocks to match those dependencies.

For example, you my have a context that sets up a valid AR object, with several tests against it. Inside the scope of that context, start another context that edits that AR object, and run tests against it.

Keep in mind that when a test in a nested context runs, it runs the setup block for the outer-most context on down, in order.

If setting up related models is a pain point, check out factory girl. Using the two together makes for happy tests the world over.

This issue was closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment