How to test an each loop on scope

23 views
Skip to first unread message

Mehmet BEYDOĞAN

unread,
Oct 30, 2015, 7:33:04 AM10/30/15
to rspec
I have the following code, how can I write unit test for this method? I want to make sure 'foo' method is getting called on users in a scope.

 
def self.some_method
 users = User.some_scope
 users.each do |user|
   user.foo
 end
end

Gist: https://gist.github.com/beydogan/8d6e01b68dcda0bb4d07

Myron Marston

unread,
Oct 30, 2015, 10:55:29 AM10/30/15
to rs...@googlegroups.com
RSpec.describe User do
  describe ".some_method" do
    it "calls #foo on each user returned by the `some_scope` scope" do
      users = [ instance_spy(User), instance_spy(User) ]
      allow(User).to receive(:some_scope).and_return(users)

      User.some_method

      expect(users).to all have_received(:foo)
    end
  end
end

This isn’t necessarily the best way to test this code. In a real system, I might favor an integration test for this code depending on what the logic of some_scope and foo are, whether or not they are tested elsewhere, etc — but for an isolated unit test it’s about the best you can do.

HTH,
Myron



--
You received this message because you are subscribed to the Google Groups "rspec" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rspec+un...@googlegroups.com.
To post to this group, send email to rs...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rspec/8f5ab842-e555-494d-8dbe-9c62cf094360%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages