Intermediate TDD in Rails : Subscription Model


To create a subscription model.


We need to save the subscriptions detail in our database. Why do we need to save it in our database? Because we can send credit card expiration emails for credit cards that are about to expire so that our subscribers can update their credit card on our site.

We will store the subscription related information in subscription model. It will contain plan_name (plan id of the stripe plan), stripe_customer_token, expiration month, year and last 4 digits of the credit card.


Step 1

Create the subscription model.

$rails g model subscription

Step 2

Change the create_subscriptions.rb file:

class CreateSubscriptions < ActiveRecord::Migration
  def change
    create_table :subscriptions do |t|
      t.string   :plan_name
      t.string   :stripe_customer_token
      t.string   :last4digits, limit: 4
      t.integer  :expiration_month, limit: 4
      t.integer  :expiration_year,  limit: 4

      t.integer  :user_id

      t.timestamps null: false

Step 3

Create the app/models/subscription_spec.rb

require 'rails_helper'

describe Subscription do
  it 'belongs to user' do
    subscription =

    expect(subscription.respond_to?(:user)).to be true

Step 4

Run the test:

$rspec spec/models/subscription_spec.rb

It fails.

Step 5


belongs_to :user  

declaration to subscription.rb. Run the test. It passes.


In this lesson we created the subscription model to save the subscription details in the database.

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.