【问题标题】:rails rspec expected is not json预期的rails rspec不是json
【发布时间】:2015-10-15 07:09:53
【问题描述】:

我的规范似乎没有正常运行,或者我的代码没有。

这是我的测试:

describe 'GET #show' do
  before(:each) do
    @os = FactoryGirl.create :deployer_os
    get :os
  end

  it 'returns all operating systems' do
    os_response = json_response
    expect(os_response).to eql @os
  end

  it { should respond_with 200 }
end

工厂:

FactoryGirl.define do
  factory :deployer_os, :class => 'DeployerOs' do
    platform 'darwin'
    version '10.10'
    description 'Yosemite'
  end
end

结果:

Failure/Error: expect(os_response).to eql @os

   expected: #<DeployerOs id: 120, platform: "darwin", version: "10.10", description: "Yosemite", created_at: "2015-10-15 07:03:44", updated_at: "2015-10-15 07:03:44">
        got: {:deployer=>[{:id=>120, :platform=>"darwin", :version=>"10.10", :description=>"Yosemite", :created_at=>"2015-10-15T07:03:44.642Z", :updated_at=>"2015-10-15T07:03:44.642Z"}]}

   (compared using eql?)

   Diff:
   ...

我不确定如何解决这个问题?我得到了我想要的结果,但我认为我的测试编写不正确。

更新

像这样修改我的测试是可行的,但我想知道这是否是完成此任务的最佳方法?

describe 'GET #show' do
  before(:each) do
    @os = JSON.parse((FactoryGirl.create :deployer_os).to_json, symbolize_names: true)
    get :os
  end

  it 'returns all operating systems' do
    os_response = json_response
    expect(os_response).to eql @os
  end

  it { should respond_with 200 }
end

【问题讨论】:

    标签: ruby-on-rails ruby json rspec


    【解决方案1】:

    您有 json 作为响应,但与 object 比较,为什么? 尝试下一个:

    @os.to_json
    

    但是@os - 它是单个对象,并且在响应中您有一个数组。 为了做出好的决定,你必须考虑你想从请求中得到什么。

    【讨论】:

    • 对,所以我需要将我的对象更改为 json。我认为这会起作用:@os = JSON.parse((FactoryGirl.create :deployer_os).to_json, symbolize_names: true) 有没有更好的方法来编写/完成这个?
    • 最终做了我在上面评论中概述的事情。这个答案让我找到了解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多