rspec(5) - mock

没有测试的代码就是耍流氓

  1. rspec(1) - summary
  2. specs(2) - model
  3. specs(3) - controller
  4. specs(4) - request
  5. specs(5) - mock
  6. [specs(6) - mailer]
  7. [specs(7) - view]
  8. [specs(8) - routing]
  9. [specs(9) - helper]
  10. [specs(10) - factory-girl]
  11. [specs(11) - fake other gems]
  12. [specs(12) - sidekiq]
  13. [specs(13) - db migration]
  14. [specs(14) - timecop]
  15. [specs(15) - jenkins]

here we talk about rspec-mock
before we start to test our code, we need to prepare our sample data, it is so bored to create many objects repeatly in our test cases.
of course, we write helper methods to save time. but this method is not flexible enough. because sometimes we want to change our object attributes
we hope there is a method which provide a with any attributes and method accessible, and it is so opened that we can change it easily.
yes, what you are looking for is mock - rspec-mock
it provides so many useful features. let's talk about it.

object

user = double('user') 

now, you got a user object.
assume it has name and 'sex`

user = double(:user, name: 'zql', sex: 'male')
# we access user's attributes
user.name.should eq 'zql'
v.sex.should eq 'male'

it looks like a OpenStruct.

stub methods

we can stub a method to an existed object.

user = double()
allow(user).to receive(:email) { "mr.zouqilin@gmail.com" }
expect(user.email).to be"mr.zouqilin@gmail.com"

stub multiple methods to a existed object

user = double()
allow(user).to receive_messages(:foo => 2, :bar => 3)
expect(user.foo).to eq 2
expect(user.bar).to eq 3

test method call

user = double()
expect(user).to receive(:foo)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,862评论 0 23
  • 从很小的时候开始,常常做一个几乎一模一样的梦: 一只灰色的小鸟,在冷峻的峭壁悬崖边,探头啄食一颗艳红的樱桃...
    nan_jia_gg阅读 445评论 2 7
  • “很快你就八十二岁了。身高缩短了六厘米,体重只有四十五公斤。但是你一如既往的美丽、优雅、令我心动。我们已经在一起度...
    于阿心阅读 582评论 0 4
  • 工作满两年,转眼也就一瞬间,老爸三番五次打电话回家去相亲,谁谁家的姑娘快30岁了,还没有对象,家人愁死了,我可...
    叙渡阅读 250评论 0 0
  • 孔圣人提出中庸之道,中国盛行几千年。不偏不倚,折中调和的处事态度世人都知道。你在房间里,觉得房间通风不好想开个窗,...
    wa牛阅读 189评论 1 1