gpt4 book ai didi

ruby-on-rails - 如何测试方法是否在 RSpec 中被调用但不覆盖返回值

转载 作者:行者123 更新时间:2023-12-04 13:22:28 25 4
gpt4 key购买 nike

已经有questions与此类似,但它们都将返回值覆盖为 nil除非 .and_return也被称为

问题

我想知道是否有一种方法可以检查是否使用 expect_any_instance_of(Object).to receive(:somemethod) 调用了一个方法并且正常运行,不会覆盖或影响.somemethod的返回值.

  • rspec-3.4.0
  • rails 4.2

  • 考虑以下:
    # rspec
    it 'gets associated user' do
    expect_any_instance_of(Post).to receive(:get_associated_user)
    Manager.run_processes
    end

    # manager.rb
    class Manager
    def self.run_processes
    associated_user = Category.first.posts.first.get_associated_user
    associated_user.destroy!
    end
    end

    上面的规范虽然有效,因为 :get_associated_userrun_processes 中被调用,但是它引发 NoMethodError: undefined method 'destroy!' for NilClass正是因为我 mock 了 :get_associated_user对于任何 Post 实例。

    我可以添加一个 .and_return方法如 expect_any_instance_of(Post).to receive(:get_associated_user).and_return(User.first)这样它就可以在不引发该错误的情况下工作,但这已经是一个模拟返回值(这可能会影响它下面的其余代码),而不是它在调用方法时应该返回的正确预期值。

    但是我可以指定 .and_return(correct_user)哪里 correct_user是返回值与正常运行相同的用户。但是,这需要我模拟序列中的每个返回值 Category.first.posts.first.get_associated_user只是为了让它正常工作。实际问题比上面复杂得多,因此在我的情况下, stub 并不是真正可行的解决方案。

    最佳答案

    You can use and_call_original on the fluent interface to "pass through" the received message to the original method.

    https://www.relishapp.com/rspec/rspec-mocks/v/2-14/docs/message-expectations/calling-the-original-method


    expect_any_instance_of(Post).to receive(:get_associated_user).and_call_original

    然而使用 expect_any_instance_of可能会告诉您您有代码异味,您应该测试行为 - 而不是实现。
    # test what it does - not how it does it.
    it 'destroys the associated user' do
    expect { Manager.run_processes }.to change(Category.first.posts.first.users, :count).by(-1)
    end

    关于ruby-on-rails - 如何测试方法是否在 RSpec 中被调用但不覆盖返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35455670/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com