【发布时间】:2021-01-04 12:45:22
【问题描述】:
你好,我是 Rails 新手
我正在编写使用 rspec gem 的测试用例
在我的控制器中,我有编辑功能。我有编辑功能之前的操作 这是我的控制器
before_action :authorize_user, only: %i[edit update destroy]
def edit
end
**private**
def authorize_user
id = Question.find(params[:id]).user_id
redirect_to root_path if id != current_user.id
end
这是我的 rspec/requests/question_rspec.rb
describe "GET /edit" do
before do
sign_in(create(:user)) # Factory Bot user
end
it "render a successful response" do
question = create(:question) #Factory bot question
# question.user = current_user
question.save
get edit_question_url(question)
expect(response).to be_successful
end
end
我收到类似
的错误Failure/Error: expect(response).to be_successful
expected `#<ActionDispatch::TestResponse:0x00005652448f4c50 @mon_data=#<Monitor:0x00005652448f4c00>, @mon_data_..., @method=nil, @request_method=nil, @remote_ip=nil, @original_fullpath=nil, @fullpath=nil, @ip=nil>>.successful?` to be truthy, got false
# ./spec/requests/questions_spec.rb:105:in `block (3 levels) in <main>'
谁能告诉我
【问题讨论】:
-
只需注释掉 before_action 并再次检查,我认为 before_action 会导致此问题
-
我删除了之前的操作。现在它成功了。但是需要使用 authorize_user 函数进行测试。
-
只需将调试器放在他们的位置上,然后找出用户未从他们那里获得授权的原因,或者我不熟悉您使用的 santax,您能否详细说明一下这个 Question.find(params[:id]) .user_id ?
标签: rspec ruby-on-rails-5 rspec-rails ruby-on-rails-6 rspec3