Skip to content
abril 1, 2009 / cassiomarques

Testing calls to named scopes in controller specs

It’s very common to have actions that call named scopes that we defined in our models. How could we test this in our controllers specs using Rspec? For a simple case, where we have a single named_scope call, we can do something like the following:

describe 'pending_orders action' do
  it "should search for the pending orders" do
    Order.should_receive(:pending).and_return([mock_model(Order, :status => Order::PENDING)])
    get :pending_orders
  end
end
def pending_orders
  @orders = Order.pending
end

But what if we have several chained calls to named scopes? For instance, if we want to query for all the pending orders and then order them by date, how could we write our spec? The problem here is that we cannot do something like we did in the above example, since the returned array of mocks don’t know how to respond to the respective method (that in our case could be called ordered_by). The solution is to mock every named scope call and return the class on which we’re calling the named scope, until the last but one call. The last call can return the array of mocks or anything else that makes sense in your test.

describe 'pending_orders action' do
  it "should search for the pending orders ordered by creation date" do
    Order.should_receive(:pending).and_return(Order)
    Order.should_receive(:ordered_by).with(:created_at).and_return([mock_model(Order, :status => Order::PENDING)])
    get :pending_orders
  end
end
def pending_orders
  @orders = Order.pending.ordered_by(:created_at)
end

For more named scope calls, all you have to do is to repeat this approach. We guarantee that our named scopes are correctly called, our tests pass and we can go home.

Deixe uma resposta

Preencha os seus dados abaixo ou clique em um ícone para log in:

Logotipo do WordPress.com

Você está comentando utilizando sua conta WordPress.com. Sair / Alterar )

Imagem do Twitter

Você está comentando utilizando sua conta Twitter. Sair / Alterar )

Foto do Facebook

Você está comentando utilizando sua conta Facebook. Sair / Alterar )

Foto do Google+

Você está comentando utilizando sua conta Google+. Sair / Alterar )

Conectando a %s

%d blogueiros gostam disto: