Skip to content

Step12: Creating a Posts Model for Testing and Demo

Lev Brie edited this page Jul 31, 2013 · 6 revisions
  1. First let's generate a Post model so that we'll have some data to work with (and we'll connect to our user_id so that each post will actually belong to the user that creates the post): $ zeus g model Post content:text user_id:integer. If you'd like to display posts in reverse order of creation, you can optionally add an index to the migration file:

class CreatePosts < ActiveRecord::Migration def change create_table :posts do |t| t.text :content t.integer :user_id

  t.timestamps
end
add_index :posts, [:user_id, :created_at]

end end ```

Then run $ rake db:migrate and $ rake db:migrate RAILS_ENV=test since this will not be done automatically for you if you're using postgres.

  1. Add some minimal testing to spec/models/post_spec.rb just to make sure when we add our associations into our models, everything works as expected:

require 'spec_helper'

describe Post do let(:user) { FactoryGirl.create(:user) } before { @post = user.posts.build(content: "Some content.") }

subject { @post } it { should respond_to(:content) } it { should respond_to(:user_id) } it { should respond_to(:user) } its(:user) { should eq user }

it { should be_valid }

describe "when user_id is not present" do before { @post.user_id = nil } it { should_not be_valid } end end ```

  1. Add belongs_to :user and validates :user_id, presence: true to app/models/post.rb

  2. Add has_many :posts to app/models/user.rb

  3. Make sure that the user responds to posts in your user_spec with it { should respond_to(:posts) } The tests should now pass.