【问题标题】:How to test for object attributes using Rspec如何使用 Rspec 测试对象属性
【发布时间】:2020-02-12 00:16:50
【问题描述】:

我正在尝试测试控制器中 show 方法的 reponse.json 输出:

describe "#show" do
 let!(:animal){create(:animal, name:"Cat"}
 let(:params) {{id: animal.id}}

 subject {get :show, params: params}

 context "when animal campaign exists" do
  it "should have the expected keys" do
    subject

    response_json = JSON.parse(response.body)
    expected_keys = [
      "animal_name",
      "id", 
      ]
      expect(response_json).to include(*expected_keys)

输出的预期对象未与expected_keys 进行比较:

  expected {"animal_name" => "Cat, "animal_id" => 6999} 
  Diff:
       @@ -1,23 +1,23 @@
       -["animal_name",
       - "animal_id"]

如何查看expected_keys

【问题讨论】:

  • 试试expect(response_json.keys).to include(*expected_keys)

标签: ruby-on-rails ruby rspec


【解决方案1】:

虽然你可以使用:

expect(response_json.keys).to include [""animal_name", "id"]

失败消息将非常神秘,因为它没有告诉我们您实际尝试测试的内容。

稍微好一点的是:

expect(response_json).to have_key "animal_name"
expect(response_json).to have_key "animal_id"

但您实际上可以针对模型测试 JSON 的正确性:

expect(response_json).to include({
  "animal_name" => "Cat"
  "animal_id" => animal.id
})

【讨论】:

    【解决方案2】:

    这感觉像是一个奇怪的测试,但你可以从response.body 映射出键。

    我不知道你的控制器是什么样的,但我猜想有一些相关的事情发生在你的回复前面animal_

    这样不是更好的测试吗?

    describe 'GET show' do
      it 'will show an animal campaign' do
        get :show, params: { id: animal.id }
        expect(response.parsed_body).to include 'animal_name'
      end
    end
    

    从你应该通过的输出来看,虽然我不太确定你到底在测试什么。

    【讨论】:

      猜你喜欢
      • 2017-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-10
      • 2023-03-08
      • 1970-01-01
      • 2017-10-20
      相关资源
      最近更新 更多