Ruby on rails 使用RSpec进行创建者|管理员|版主权限测试
我对RSpec测试的理解有困难。阅读文档、教程,但仍然不了解如何测试以下案例。 我需要测试的编辑权限只允许笔记的创建者,管理员和版主。 顺便说一句,它在浏览器中工作,但我想学习如何为类似的东西编写测试 控制器:Ruby on rails 使用RSpec进行创建者|管理员|版主权限测试,ruby-on-rails,ruby,rspec,factory-bot,Ruby On Rails,Ruby,Rspec,Factory Bot,我对RSpec测试的理解有困难。阅读文档、教程,但仍然不了解如何测试以下案例。 我需要测试的编辑权限只允许笔记的创建者,管理员和版主。 顺便说一句,它在浏览器中工作,但我想学习如何为类似的东西编写测试 控制器: before_action :set_note_with_permissions, only: [:edit, :update, :destroy] def edit respond_to do |format| format.js { } fo
before_action :set_note_with_permissions, only: [:edit, :update, :destroy]
def edit
respond_to do |format|
format.js { }
format.html { }
end
end
def set_note_with_permissions
current_note = Note.find(params[:id])
if current_user && (current_note.user.id == current_user.id || current_user.moderator? || current_user.admin?)
@note = Note.find(params[:id])
else
# redirects / flashes / etc.
end
end
FactoryGirl固定装置:
用户:
注:
我的测试逻辑是:
require "rails_helper"
describe NotesController do
describe "edit action" do
context "when try to edit note" do
it "is your note" do
note = create(:note) # => note.user.id == 1 (couse of association)
user = create(:user) # => user.id == 2
sign_in user
get "notes/#{note.id}/edit"
expect(response).not_to render_template("edit")
end
end
end
end
但正如你所预料的那样,它不适用于
ActionController::UrlGenerationError:
No route matches {:action=>"notes/1/edit", :controller=>"notes"}
我不要求你为我写代码。只需指向必要的文档和技术。我需要Copybara吗,还是纯RSpec可以 根据您收到的错误消息,我认为您的问题在于如何调用
get
。您不应该将URL作为字符串传递,而应该将操作的名称作为符号传递。所以在你的情况下,你可以改变
get "notes/#{note.id}/edit"
到
它应该会起作用
如您所见,您可以将控制器操作的附加参数作为散列传入。您可以在第一个和最后一个示例中看到这方面的示例。当您尝试在浏览器上访问它时,它是否起作用?是的,它起作用,但我真的想学习TDD这样强大的功能,以备将来:)只要确保您的问题实际上在测试中而不是在应用程序中。谢谢,我一到计算机上就会尝试您的解决方案!没问题!很高兴这有帮助:)
ActionController::UrlGenerationError:
No route matches {:action=>"notes/1/edit", :controller=>"notes"}
get "notes/#{note.id}/edit"
get :edit, id: note.id