Skip to content

Instantly share code, notes, and snippets.

@mfifth
Last active May 19, 2016 22:34
Show Gist options
  • Select an option

  • Save mfifth/09797909c8e209da03c26ff82e1aa70d to your computer and use it in GitHub Desktop.

Select an option

Save mfifth/09797909c8e209da03c26ff82e1aa70d to your computer and use it in GitHub Desktop.
require 'rails_helper'
RSpec.describe "Users can edit topics" do
let(:author) { FactoryGirl.create(:user) }
let(:forum) { FactoryGirl.create(:forum) }
let(:topic) { FactoryGirl.create(:topic, forum: forum, author: author) }
before do
login_as(author)
visit forum_topic_path(forum, topic)
click_link "Edit Topic"
end
scenario "successfully" do
fill_in "Title", with: "This is an awesome title"
fill_in "Description", with: "dude bro do you even lift? get guud brah."
click_button "Update Topic"
expect(page).to have_content "Topic has been updated."
end
end
class TopicsController < ApplicationController
before_action :verify_author, only: [:destroy, :update, :edit]
before_action :authenticate_user!, only: [:create, :new]
before_action :set_forum
before_action :set_topic, only: [:update, :destroy, :edit, :show]
def index
@topics = Topic.all
end
def new
@topic = @forum.topics.build
end
def show
end
def edit
end
def create
@topic = @forum.topics.build(topic_params)
@topic.author = current_user
if @topic.save
flash[:notice] = "Topic has been successfully created."
redirect_to [@forum, @topic]
else
flash.now[:alert] = "Topic has not been created."
render 'edit'
end
end
def destroy
@topic.destroy
flash[:notice] = "Topic has been deleted."
redirect_to @forum
end
def update
if @topic.update(topic_params)
flash[:notice] = "Topic has been updated."
redirect_to [@forum, @topic]
else
flash.now[:alert] = "Topic has not been updated."
render 'edit'
end
end
private
def topic_params
params.require(:topic).permit(:title, :description)
end
def set_forum
@forum = Forum.find(params[:forum_id])
end
def set_topic
@topic = @forum.topics.find(params[:id])
end
def verify_author
unless current_user.email == @topic.author.email
flash[:alert] = 'Only the author can edit or delete their own post.'
redirect_to forums_path
end
end
end
@mfifth
Copy link
Author

mfifth commented May 19, 2016

  1. Users can edit topics successfully
    Failure/Error: unless current_user.email == @topic.author.email
 NoMethodError:
   undefined method `author' for nil:NilClass

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment