chrishough chrishough - 1 year ago 77
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 = params[:id])

Which I am trying cover with the following test:

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

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

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

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.


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

Answer Source

Something like this should work:

allow(IntegrationProvider).to receive_message_chain(:new, :proxy_to, :find_by).and_return(yourproviderobjecthere)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download