【问题标题】:How to test that method gets called with a mix of arguments and keyword arguments in rspec?如何测试该方法被rspec中的参数和关键字参数混合调用?
【发布时间】:2016-04-06 00:17:51
【问题描述】:

我有一个这样调用的方法:

post_signup(user,
            "fb signup completed",
            app_context: current_app_id,
            description: "Automatically Populated Via #{current_app_id}")

参数是值和关键字参数的混合。我在测试中关心的是app_context。我尝试了类似的方法,但它不起作用:

it "should log an event with an app_context" do
        expect(controller).to receive(:post_signup).with(hash_including(app_context: current_app_id))

        subject
      end

和

it "should log an event with an app_context" do
        expect(controller).to receive(:post_signup).with(current_app_id, any_args)

        subject
      end

男人能做什么?

【问题讨论】:

  • 不要对好公民感到绝望,hash_including 的魔力仍然会拯救你! rubydoc.info/gems/rspec-mocks/RSpec/Mocks/…
  • 只是注意到您实际上尝试过... :D 但看起来您尝试将其作为第一个参数...但哈希是第二个参数,因此您需要类似:@987654326 @ 所以anything 匹配第一个参数(即user),然后将hash_include 用于它的其余部分(即哈希...)
  • 让这个答案@TarynEast

标签: rspec mocking


【解决方案1】:

好公民不要绝望,hash_including 的魔力仍然会拯救你!

看起来您尝试将它作为第一个参数,但哈希实际上是您的 post_signup 方法的第二个参数。第一个参数是user。

所以要制作一个有效的expect,你需要这样的东西:

expect(controller).to receive(:post_signup).with(anything, hash_including(app_context: current_app_id))

所以任何东西都匹配user,然后hash_including 用于其余部分......

【讨论】:

  • 更重要的是,这是脆性测试的标志吗?一个为了自己的利益而过于具体?我应该赌在方法调用中测试参数的位置吗?
  • 我不这么认为...尽管您可以将其全部设为哈希并使用:user => user,然后只有一个参数:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 2012-10-26
  • 2023-04-10
  • 2020-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多