chrishough chrishough - 5 months ago 13
Ruby Question

rails 4 rspec 3.4 controller test with stub

In my controller I have the following method:

def set_provider
@provider = Provider.find_by(id: params[:id])
return @provider unless @provider.active
@provider = IntegrationProvider.new(@provider.slug).proxy_to.find_by(id: params[:id])
end


Which I am trying cover with the following test:

context 'active' do
before do
@provider = FactoryGirl.create(:provider, :active)
get :show, id: @provider.id
end

it '200' do
expect(response.status).to be(200)
end

it 'assigns @provider' do
expect(assigns(:provider)).to eq(@provider)
end
end


The IntegrationProvider class is basically a child model of the Provider model. Since these can be dynamic, and I am using FactoryGirl I am thinking a stub would work best here. In the code base the slugs correspond to folders so I do not want to test that other class in this controller class. I will save that for my lib class tests.

Question

How would you stub that IntegrationsProvider class so it returns the Provider model?

Answer

Something like this should work:

allow(IntegrationProvider).to receive_message_chain(:new, :proxy_to, :find_by).and_return(yourproviderobjecthere)