I'm doing this test controller with RSpec on post_controller, but I'm having difficult to evaluate the users who don't have permission for check the categories.
expect(posting.categories).to have_unchecked_field("Sports")
This test it's like a way for a user don't hacking the post categories.
The
context "restrictions for users on posts who" do
let(:user) { create(:user) }
let(:category) { create(:category)}
let(:posting) { Post.create(title: "State transitions", subtitle: "Can't be hacked.", content: "State transitions now they can't be hacked anymore.", author: user) }
before :each do
posting.categories << category
assign_role!(user, :editor, posting)
sign_in user
end
it "can edit a post, but not tag them" do
put :update, { id: :posting.to_param, title: "Editing post for editors!",
content: "The editor users, they cannot tag a post",
tag_names: "these are tags" },
post_id: posting.id
posting.reload
expect(posting.tags).to be_empty
end
it "can edit a post, but not check the categories" do
put :update, { id: :posting.to_param,
title: "Editing post for editors!",
content: "The editor users, they cannot check categories",
category_ids:["Sports"] },
post_id: posting.id
posting.reload
expect(posting.categories).to have_unchecked_field("Sports")
end
end
end
form:
- if policy(post).change_category?
= f.association :categories, label: "Select the Categories:", as: :check_boxes , collection: @categories.map{|c| [c.name, c.id]}, include_hidden: false
So I'm using the private method sanitizing_parameters for deleting the parameters if a user don't have a permission.
post_controller.rb
def update
authorize @post, :update?
@post.author = current_user
if @post.update(sanitized_parameters)
flash[:notice] = "Post has been updated."
redirect_to @post
else
flash.now[:alert] = "Post has not been updated."
render "edit"
end
end
...
private
def post_params
params.require(:post).permit(:title,
:subtitle,
:content,
:tag_names,
:attachment,
:attachment_cache,
:remove_attachment,
:remote_attachment_url,
category_ids:[])
end
def sanitized_parameters
whitelisted_params = post_params
unless policy(@post).change_category?
whitelisted_params.delete(category_ids:[])
end
unless policy(@post).tag?
whitelisted_params.delete(:tag_names)
end
whitelisted_params
end
error:
Failures:
1) PostsController restrictions for users on posts who can edit a post, but not check the categories
Failure/Error: expect(posting.categories).to have_unchecked_field("Sports")
expected to find field "Sports" that is not checked but there were no matches