0

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?

Vega
  • 27,856
  • 27
  • 95
  • 103
ananyo2012
  • 63
  • 9
  • I don't know Ruby, but what you are describing it creating a "fake", not a stub. I try to avoid them like the plague because you technically have to write unit tests for them to ensure they are behaving predictably. I may not be understanding your problem correctly, but I would write two tests and use two different stubs. One stub will be where `:uid` = 0 the other test will use a stub where the `:uid` is some value greater than or equal to 1. – Andrew Eddie May 30 '16 at 07:08

1 Answers1

0

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])
Tom Lord
  • 27,404
  • 4
  • 50
  • 77
  • I have tried this earlier. It won't work since instances used during rendering the page are different from the stubbed instances.So we need to specifically stub instances of the class using `uid`. – ananyo2012 May 19 '16 at 14:12