美文网首页
rspec(5) - mock

rspec(5) - mock

作者: auguszou | 来源:发表于2017-05-19 00:01 被阅读0次

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

    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)
    

    相关文章

      网友评论

          本文标题:rspec(5) - mock

          本文链接:https://www.haomeiwen.com/subject/ckmexxtx.html