Chris Hough
Chris Hough

Reputation: 3558

Controller test with stub using Rails 4 and Rspec 3.4

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?

Upvotes: 0

Views: 50

Answers (1)

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

Something like this should work:

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

Upvotes: 2

Related Questions