Challenge 3: A Request Spec for Authorization — Solution # spec/requests/posts_spec.rb RSpec.describe "Posts", type: :request do it "lets the author destroy their own post" do post = create(:post, user: current_user) sign_in current_user delete post_path(post) expect(response).to redirect_to(posts_path) expect(Post.exists?(post.id)).to be false end it "rejects destroy from a non-admin, non-author user" do post = create(:post) sign_in create(:user) delete post_path(post) expect(response).to redirect_to(root_path) # Pundit's rescue_from, rails2-2 expect(Post.exists?(post.id)).to be true end end =begin Notes: - create(:post, user: current_user) uses the Challenge 2 factory, overriding just the user association so the post is owned by whichever user the spec signs in as -- matching PostPolicy#destroy? checking record.user == user. - The first example asserts two things: the redirect Rails sends on success, and that the post is actually gone from the database afterward -- checking only the response code would miss a bug where destroy silently failed but still redirected. - The second example uses a post created without an explicit user (a different, factory-default author) and signs in as yet another new user -- neither the post's author nor an admin -- so PostPolicy#destroy? returns false and Pundit's rescue_from (from rails2-2's ApplicationController) redirects to root_path instead of destroying anything. - Post.exists?(post.id) after the rejected attempt confirms the record still exists -- verifying the policy didn't just redirect while destroying the record anyway. =end