【发布时间】:2018-04-12 18:07:24
【问题描述】:
我无法通过这些测试:
# user_controller_spec.rb
describe "GET #edit" do
user = FactoryBot.create(:user)
it "returns http success" do
get :edit, params: {id: user.hash_id}
expect(response).to have_http_status(:success)
end
it "renders :edit" do
get :edit, params: {id: user.hash_id}
expect(response).to render_template :edit
end
end
这个输出:
Failures:
1) UsersController when authenticated GET #edit returns http success
Failure/Error: @user = User.friendly.find(params[:id])
ActiveRecord::RecordNotFound:
can't find record with friendly id: "cWLxnN9DS43g"
# /Users/speasley/.rvm/gems/ruby-2.4.1/gems/friendly_id-5.2.3/lib/friendly_id/finder_methods.rb:23:in `find'
# ./app/controllers/users_controller.rb:109:in `set_user'
# /Users/speasley/.rvm/gems/ruby-2.4.1/gems/rails-controller-testing-1.0.2/lib/rails/controller/testing/template_assertions.rb:61:in `process'
# /Users/speasley/.rvm/gems/ruby-2.4.1/gems/devise-4.4.3/lib/devise/test/controller_helpers.rb:35:in `block in process'
# /Users/speasley/.rvm/gems/ruby-2.4.1/gems/devise-4.4.3/lib/devise/test/controller_helpers.rb:102:in `catch'
# /Users/speasley/.rvm/gems/ruby-2.4.1/gems/devise-4.4.3/lib/devise/test/controller_helpers.rb:102:in `_catch_warden'
# /Users/speasley/.rvm/gems/ruby-2.4.1/gems/devise-4.4.3/lib/devise/test/controller_helpers.rb:35:in `process'
# /Users/speasley/.rvm/gems/ruby-2.4.1/gems/rails-controller-testing-1.0.2/lib/rails/controller/testing/integration.rb:12:in `block (2 levels) in <module:Integration>'
# ./spec/controllers/users_controller_spec.rb:132:in `block (4 levels) in <top (required)>'
但是如果我puts来比较输入/输出:
# users_controller.rb
before_action :set_user, only: [:show, :edit, :update, :destroy]
...
def set_user
@user = User.friendly.find(params[:id])
puts "#{params[:id]}, @user.hash_id"
end
我得到的 id 与失败消息中的不同。这些不应该匹配吗?我无法弄清楚为什么测试完全失败,但比较这些似乎是一个合乎逻辑的起点。在set_user 方法中,我可以puts 找到的用户及其属性,但无法通过测试。有什么想法吗?
【问题讨论】:
-
如果在此行之前引发错误,您如何查看
puts返回的内容? -
这是一个 rspec 失败消息,而不是 Rails 错误。规范失败了,Rails/ActiveRecord 处理得很好,所以我可以放。
-
显示整个错误信息和回溯
-
我已经编辑了我的原始帖子,@chumakoff。奇怪的是,直接来自
set_user的puts表明用户已成功查询(但hash_id与抛出错误中的不匹配)。
标签: ruby-on-rails rspec factory-bot friendly-id