What's the difference between RSpec's subject and let? When should they be used or not?

前端 未结 3 879
迷失自我
迷失自我 2020-12-22 17:04

http://betterspecs.org/#subject has some info about subject and let. However, I am still unclear on the difference between them. Furthermore, the S

3条回答
  •  無奈伤痛
    2020-12-22 17:47

    Subject and let are just tools to help you tidy up and speed up your tests. People in the rspec community do use them so i wouldn't worry about whether it's ok to use them or not. They can be used similarly but serve slightly different purposes

    Subject allows you to declare a test subject, and then reuse it for any number of following test cases afterward. This reduces code repetition (DRYing up your code)

    Let is an alternative to before: each blocks, which assign test data to instance variables. Let gives you a couple of advantages. First, it caches the value without assigning it to an instance variable. Second, it is lazily evaluated, which means that it doesn't get evaluated until a spec calls for it. Thus let helps you speed up your tests. I also think let is easier to read

提交回复
热议问题