ananyo2012
ananyo2012

Reputation: 63

Stub specific instances of a class in a functional test

I want to test that a specific icon gets displayed in the view for a User with a streak more than X no of days. So I need to stub a streak method of the User model.But I want that it stubs the method only for a specific user based on its uid. The test code is given below.

test "should display an icon for users with streak longer than 7 days" do
    node = node(:one)
    User.any_instance.stubs(:streak).returns([8,10])
    get :show, 
        author: node.author.username, 
        date: node.created_at.strftime("%m-%d-%Y"),
        id: node.title.parameterize
    assert_select ".fa-fire", 1
end

The return value is an array, the first value in the array is the no of days in the streak and the second value is the no of posts in that streak.

The line User.any_instance.stubs(:streak).returns([8,10]) stubs any instance of the User class. How can I stub it so that it stubs only those instances where :uid => 1?

Upvotes: 0

Views: 433

Answers (1)

Tom Lord
Tom Lord

Reputation: 28285

Sounds like you should be stubbing the specific instance, rather than the class itself.

User.where.not(uid: 1).each do |user|
  user.stubs(:streak).returns([8,10])
end

Or maybe (I can't say for sure without more context), you could optimise this by just doing:

node.author.stubs(:streak).returns([8,10])

Upvotes: 0

Related Questions