简体   繁体   English

Rails:如何测试执行mysql查询的辅助方法

[英]Rails: how do I test a helper method that executes a mysql query

I'm having a method in a helper, that determines whether a user has a specific flag ( enabled ), based on tags and a code, stored in a cookie. 我在助手中有一个方法,该方法根据存储在cookie中的标签和代码来确定用户是否具有特定标志( enabled )。

def user_enabled?
  Code.joins({tags: :user}).
    where(code: cookies[:user_code]).
    where(users: {enabled: true})
    exists?
end

Basically, a tag is associated with a user and a code with a tag. 基本上,标签与用户关联,代码与标签关联。

I'm not really sure how to recreate that in my specs, so that the query executes all the records required. 我不太确定如何在我的规范中重新创建它,以便查询执行所需的所有记录。 So far I have: 到目前为止,我有:

it 'returns true when enabled is checked' do
  tag = create(:tag, user: create(:user, enabled: true))
  Code.create(code: 'enabled', tags: [tag])
  cookies[:user_code] = 'enabled'
  expect(user_enabled?).to be_truthy
end

But that returns false and I'm not really sure what I'm missing. 但这返回假,我不确定我到底缺少什么。

Here's what I did to fix this: 这是我为解决此问题所做的工作:

Context 'some context'
  let!(:tag) { create(:tag, user: create(:user)) }
  let!(:code) { create(:code, code: 'enabled', tags: [tag]) }

  it 'returns true when enabled is checked' do
    cookies[:user_code] = 'enabled'
    expect(user_enabled?).to be_truthy
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM