Intermediate TDD in Rails : Controller Test for Subscription


To implement the controller for subscription feature.


Step 1

Let's now go up the layer and deal with the controller now. We need a user to be logged in. Add:

RSpec.configure do |config|  
  config.include Devise::TestHelpers, :type => :controller


to the rails_helper.rb.

Step 2

Now we can use sign_in devise test helper in our test.

    it 'should save the subscription details', focus: true do
      Stripe.api_key = 'sk_test_watHqWl2XD88WHqhknk7sqXN'
      Stripe.api_version = "2015-02-18"  

      user = User.create(email: '', password: '12345678')

      expect(Subscription).to receive(:save_details)

      post :create, params: { stripeToken: 1, plan_name: 'gold' }      

We are using mock here because the save_details is our custom method. It is not a third-party library method. The save_details has already been tested in the model test.

Step 3

Run the test. The error is:

 expected: 1 time with any arguments
   received: 0 times with any arguments  

Step 4

Change the subscriptions_controller create method:

  def create
    stripe_customer = StripeGateway::Subscription.create(, params[:stripeToken], params[:plan_name])
    Subscription.save_details(stripe_customer, current_user, params[:plan_name])

The test passes.


In this lesson we implemented the controller to handle the subscription feature by using a mock.

Related Articles

Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.