Week 8, day 6
I present to you the chronicle of my troubleshooting for the weekend challenge, Instagram clone in Ruby on Rails using Rspec for testing. Warning: This is a 'no such thing as stupid questions' zone!
I've decided to start my testing/coding with uploading an aimage description first and because of how I wrote my test
1 - I had to remind myself of how to make button text in erb.
scenario 'prompts user to enter a description, then displays the new description' do
visit '/images'
click_link 'Upload Image'
fill_in 'Description', with: 'My face'
click_button 'Upload'
expect(page).to have_content 'My face'
expect(current_path).to eq '/images'
end
<%= form_for Image.new do |i| %>
<%= i.label :description %>
<%= i.text_field :description %>
<%= i.submit "Upload" %>
<% end %>
2 - Hit a snag navigating my routes for what happens after a user comments, the key was redirecting back to the image's path, passing the id as a param
scenario 'allows users to comment on an image' do
visit '/images'
click_link 'Comment on My face'
fill_in "Comment", with: "so so"
click_button 'Comment'
expect(page).to have_content('so so')
end
def new
@image = Image.find(params[:image_id])
@comment = Comment.new
end
def create
@image = Image.find(params[:image_id])
@image.comments.create(comment_params)
redirect_to image_path(@image)
end
3 - Undoing database migrations.... Ok I knew it would come to this. So I messed up while generating a new migration but the revert wasn't so painful.
First to get the last working migration's ID.
bin/rake db:migrate:status
Then
bin/rake db:migrate VERSION="###"
bin/rake db:migrate
Source Then the shenanigans can carry on.
4 - Creating columns in tables and associations in controllers
The Test:
describe Comment, type: :model do
it { should belong_to(:user) }
end
In Terminal/Bash:
bin/rails g migration AddUserIdToComments user:belongs_to
bin/rake db:migrate
In Model:
class Comment < ActiveRecord::Base
belongs_to :image
belongs_to :user
validates :comment, length: {minimum: 3}
end
In Controller:
def create
@image = Image.find(params[:image_id])
@comment = @image.comments.new(comment_params)
@comment.user_id = current_user.id
if @comment.save
redirect_to image_path(@image)
else
render 'new'
end
end
5 - Adding a 'Like' button Source 1
scenario 'a user can like an image, which updates the image likes count' do
visit '/'
click_link 'Like'
expect(page).to have_content('1 like')
end
The Controller redirects back to the root path, avoiding the need for unnecessary code
In Controller:
def create
@image = Image.find(params[:image_id])
@image.likes.create
redirect_to images_path
end
In Model:
belongs_to :image
belongs_to :user
In View:
<%= pluralize image.likes.count, 'likes' %>
<%= link_to "Like", image_likes_path(image), remote: true, method: :post %>
The the above described steps need to be done to migrate the database, adding necessary columns.