Intermediate TDD in Rails : Controller Test for Subscription

Objective


To implement the controller for subscription feature.

Steps


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

end

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: 'bugs@disney.com', password: '12345678')
      sign_in(User.last)   

      expect(Subscription).to receive(:save_details)

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

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(current_user.email, params[:stripeToken], params[:plan_name])
    Subscription.save_details(stripe_customer, current_user, params[:plan_name])
  end

The test passes.

Summary


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


Related Articles


Software Compatibility Best Practices

I spoke to some of the most talented and experienced software developers. I have created a guide that is filled with valuable insights and actionable ideas to boost developer productivity.

You will gain a better understanding of what's working well for other developers and how they address the software compatibility problems.

Get the Guide Now