Rails Stub在模块内部的一个变量 [英] Rails Stub a variable inside module
问题描述
我为此模块写了一个单元测试,想对来自应用程序控制器的current_account
变量存根.
(它的全局方法写在应用程序控制器中)
I wrote a unit test for this module and want to stub current_account
variable which comes from application controller.
(its global method written in application controller)
Module Foo
def querying_result(criteria)
User.find_by_account(current_account).where(criteria: criteria)
end
end
我尝试了
Foo.stubs(current_account: @user.account).returns(@user.account)
Foo.any_instance.stub(current_account:@user.account).and_return(@user.account)
我的测试文件
class FooTest << ActiveSupport::TestCase
context "querying the result"
setup do
@user = User.first
end
should "return all users" do
users = querying_result(criteria)
assert_equal users.count, 1
end
end
我在这里想念什么?
推荐答案
据我所知,Foo
模块可能直接包含在FooTest中.
From what I see Foo
module might be included directly in the FooTest.
这很奇怪,但是要使其正常工作,您可能(仅猜测)存根self
而不是Foo
(self.stubs...
).
This is weird, but to make it work you should probably (only guessing) stub self
not Foo
(self.stubs...
).
但这不是您应该测试模块的方式.
IMO应该测试包含此模块的类.而且,如果您不想将测试与任何特定的类相关联,请在规范内创建一个.
IMO one should test classes that include this module. And if you don't want to tie your test to any specific class - create one inside the spec.
@dummy_class = Class.new do
include Foo
def initialize(current_account)
@current_account = current_account # you can control this now by injecting the account on object creation
end
attr_accessor :current_account
end
并在测试中类似
@foo = @dummy_class.new(@user)
assert_equal(@foo.querying_result(criteria).count, 1)
您还可以跳过initialize
部分,仅存根@foo
对象.
You can also skip the initialize
part and just stub @foo
object.
这篇关于Rails Stub在模块内部的一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!