Created
February 2, 2014 20:00
-
-
Save randalmaile/8773918 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## RSpec favorites_controller.rb | |
require 'spec_helper' | |
describe FavoritesController do | |
before :each do | |
@bookmark = create(:bookmark) | |
@favorite = create(:favorite) | |
end | |
describe "POST #create" do | |
it "saves a new favorite to the database" do | |
expect{ post :create, {bookmark_id: @bookmark.id} , favorite: attributes_for(:favorite) }.to change(Favorite,:count).by(1) | |
end | |
end | |
end | |
## After running rspec in terminal | |
Failures: | |
1) FavoritesController POST #create saves a new favorite to the database | |
Failure/Error: expect{ post :create, {bookmark_id: @bookmark.id} , favorite: attributes_for(:favorite) }.to change(Favorite,:count).by(1) | |
NoMethodError: | |
undefined method `favorites' for nil:NilClass | |
# ./app/controllers/favorites_controller.rb:5:in `create' | |
# ./spec/controllers/favorites_controller_spec.rb:15:in `block (4 levels) in <top (required)>' | |
# ./spec/controllers/favorites_controller_spec.rb:15:in `block (3 levels) in <top (required)>' | |
Finished in 4.03 seconds | |
14 examples, 1 failure, 1 pending | |
Failed examples: | |
rspec ./spec/controllers/favorites_controller_spec.rb:14 # FavoritesController POST #create saves a new favorite to the database | |
## favorites_controller.rb (the actual controller) | |
class FavoritesController < ApplicationController | |
def create | |
@bookmark = Bookmark.find(params[:bookmark_id]) | |
favorite = current_user.favorites.create(bookmark: @bookmark) | |
if favorite.valid? | |
flash[:notice] = "Favorited post" | |
redirect_to :back | |
else | |
flash[:error] = "Unable to add favorite." | |
redirect_to :back | |
end | |
end | |
def destroy | |
favorite = current_user.favorites.find(params[:id]) | |
if favorite.destroy | |
flash[:notice] = "Removed favorite." | |
redirect_to :back | |
else | |
flash[:error] = "Unable to remove favorite. Please try again." | |
redirect_to :back | |
end | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment