Rails Stub a variable inside module

2019-07-14 01:48发布

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

I tried with following

Foo.stubs(current_account: @user.account).returns(@user.account)
Foo.any_instance.stub(current_account:@user.account).and_return(@user.account)

My Test file

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

what am I missing here?

1条回答
神经病院院长
2楼-- · 2019-07-14 01:55

From what I see Foo module might be included directly in the FooTest.

This is weird, but to make it work you should probably (only guessing) stub self not Foo (self.stubs...).

But this is not how you supposed to test modules.

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

and in test something like

@foo = @dummy_class.new(@user)
assert_equal(@foo.querying_result(criteria).count, 1)

You can also skip the initialize part and just stub @foo object.

查看更多
登录 后发表回答