【问题标题】:rspec and friendly_id mismatchesrspec 和friendly_id 不匹配
【发布时间】: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_userputs 表明用户已成功查询(但hash_id 与抛出错误中的不匹配)。

标签: ruby-on-rails rspec factory-bot friendly-id


【解决方案1】:

您为什么使用hash_id 作为友好ID?这是存储用户友好ID的字段吗?

有一种方法应该返回正确的友好 id 值,而不管它实际使用的是哪个字段:friendly_id

get :edit, params: {id: user.friendly_id}

【讨论】:

  • 是的,hash_id 是我存储friendly_id 的地方。所以我设置了friendly_id :hash_id。我尝试了您的建议,但得到了相同的结果。
  • 尝试用let(:user) { FactoryBot.create(:user) }替换user = FactoryBot.create(:user)
  • 没有骰子。该死。
猜你喜欢
  • 1970-01-01
  • 2011-07-23
  • 1970-01-01
  • 2015-01-16
  • 1970-01-01
  • 1970-01-01
  • 2013-11-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多