【问题标题】:Rspec checking for json responseRspec 检查 json 响应
【发布时间】:2014-08-12 19:59:44
【问题描述】:

我正在尝试创建一个mock object,我正在检查我的方法receives 是否正确param 和预期结果。

下面是我的spec

require 'spec_helper'

describe User do 

  let(:username) {"test@test.com"}
  let(:password) {"123"}
  let(:code) {"0"}

  context "when signing in" do 

    it "should sign in" do 
      user = double("user")
      expected_results = {
        "token": "123"
      }
      allow(user).to receive(:login).with({email: username, password: password, code: code})
        .and_return(expected_results)
      expect(user.login).to eq(expected_results)
    end

  end    
end

有没有办法将我的 jsonit 块分开并保留在外面?

【问题讨论】:

  • @zetetic:我看了,但没有帮助...
  • 我不清楚这个问题。您只想在示例之外设置expected_results 的值吗?您可以通过在内部上下文中添加 let 来做到这一点。
  • @zetetic:你能举出那个例子吗,因为它失败了。我也在做正确的测试方式吗?

标签: ruby-on-rails ruby json ruby-on-rails-3 rspec


【解决方案1】:

您可以在上下文块中使用let 为嵌套在其中的示例设置变量的值:

require 'spec_helper'

describe User do 

  let(:username) {"test@test.com"}
  let(:password) {"123"}
  let(:code) {"0"}

  context "when signing in" do
    let(:expected_results) { {token:"123"}.to_json }

    it "should sign in" do 
      user = double("user")
      allow(user).to receive(:login).with({email: username, password: password, code: code})
        .and_return(expected_results)
      expect(user.login).to eq(expected_results)
    end

  end    
end

我的测试方法是否正确?

如果您正在测试 User#login 方法,则不会。如果您尝试测试被存根的方法的逻辑,则不应设置存根。相反,使用真实的模型实例,也许使用工厂,并省略allow 步骤。

【讨论】:

  • 为什么我会收到这个错误...失败/错误:expect(user.login).to eq(expected_results) Double "user" received :login with unexpected arguments expected: ({:email= >"test@test.com", :password=>"123", :code=>"0"}) got: (no args) 如果消息也可能与其他 args 一起接收,请先存根默认值。
  • user.login 打了 api 并返回给我上面的响应,所以我想到了这样做吗?这是一种很好的方法吗?为什么会出现上述错误。
  • 听起来您需要模拟 API 响应,而不是 login 方法调用。为什么不发布用户模型中的相关代码?
  • pastie.org/9468099 它包含我的模型类
  • 这取决于你存根。在不知道您的测试目标的情况下,我不能说更多。花点时间阅读我在上面发布的链接——它显示了active_rest_client 的作者如何测试 gem,应该有助于决定如何设计测试策略。
【解决方案2】:

您可以在上下文中或上下文之前使用before do 块。

这里是参考: https://www.relishapp.com/rspec/rspec-core/docs/hooks/before-and-after-hooks

【讨论】:

  • 有没有我们可以创建一个 json mock 之类的东西?
猜你喜欢
  • 2011-07-06
  • 2017-07-10
  • 2019-05-05
  • 1970-01-01
  • 2011-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-13
相关资源
最近更新 更多