Rspec 检查 json 响应 [英] Rspec checking for json response

查看:41
本文介绍了Rspec 检查 json 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to create a mock object and i am checking whether my method receives the right param and expected result.

下面是我的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 块分开并保持在外面?

Is there a way to separate my json from it block and keep it outside?.

推荐答案

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

You can use let inside a context block to set the value of a variable for the examples nested within:

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 步骤.

Not if you are testing the User#login method. You should not set a stub if you are trying to test the logic of the method being stubbed. Instead, use a real model instance, perhaps using a factory, and omit the allow step.

这篇关于Rspec 检查 json 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆