-
Notifications
You must be signed in to change notification settings - Fork 0
Step12: Creating a Posts Model for Testing and Demo
-
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.
-
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 ```
-
Add
belongs_to :user
andvalidates :user_id, presence: true
toapp/models/post.rb
-
Add
has_many :posts
toapp/models/user.rb
-
Make sure that the user responds to posts in your user_spec with
it { should respond_to(:posts) }
The tests should now pass.