rspec存根记录查询

时间:2013-10-17 17:00:44

标签: ruby rspec stub

我试图将查询结果存根以检索一些记录。这是查询:

ouid = OrganizationalUnit.where("billing_id = ? AND status = 'active'", data[:billing_id]).select(:id)
user_id = User.where("group_id in (14,17) AND organizational_unit_id in (?) AND status = 'active'", ouid).select(:id).first

我试图用它来存根:

    ou_value = double'fake ou',{ 'id' => '654321' }
    select_double = double 'fake select', {'select' => [ou_value]}
    OrganizationalUnit.stub( :where).and_return(select_double)

这不起作用。我对用户表的查询如下所示:

SELECT id FROM `users` WHERE (group_id in (14,17) AND organizational_unit_id in ('--- !ruby/object:RSpec::Mocks::Mock\n__null_object: false\nname: fake ou\noptions:\n :__declared_as: Double\n') AND status = 'active') LIMIT 1

它应该是这样的:

SELECT id FROM `users` WHERE (group_id in (14,17) AND organizational_unit_id in (654321) AND status = 'active') LIMIT 1

我做错了什么?

由于

1 个答案:

答案 0 :(得分:2)

所以你想要存根这个查询:

OrganizationalUnit.where("billing_id = ? AND status = 'active'", data[:billing_id]).select(:id)

我认为这应该是

OrganizationalUnit.stub_chain(:where, :select).and_return(654321)

另一件事:在模型中的方法或范围内移动查找器总是一个好主意。通过这样做,可以更容易地存根或模拟测试内容。