Rspec checking for json response

杀马特。学长 韩版系。学妹 提交于 2019-12-25 03:24:38

问题


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

Below is my 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

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


回答1:


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

am i doing the right way of testing?

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.




回答2:


You can use a before do block in the context or before the context.

Here is the reference: https://www.relishapp.com/rspec/rspec-core/docs/hooks/before-and-after-hooks



来源:https://stackoverflow.com/questions/25273062/rspec-checking-for-json-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!