在红宝石中模仿json的反应

时间:2014-08-14 08:37:59

标签: ruby-on-rails ruby json unit-testing rspec

我从我的API获得json response。有没有办法可以模拟这个json响应来与API进行比较。

it "should find all accounts" do 
  let(:myjson) {
            "@type": "userResource",
            "createdAt": "2014-08-14T07:32:52",
            "createdBy": 2,
            "updatedAt": "2014-08-14T07:32:52",
            "updatedBy": 2,
            "email": "12@12.com",
            "name": "test",
            "password": "",
            "confirmpassword": "",
            "id": 2856,
            "accountid": 0,
            "resetpw": false,                
   }
  expect(response.body).to eq(myjson);
emd

有没有办法可以模拟json,所以我不需要在我的规范中对其进行硬编码。

1 个答案:

答案 0 :(得分:0)

我猜您在进行API调用之前有一些在数据库中创建帐户的设置,因此您可以在测试中将这些帐户序列化为JSON,并将其与API响应进行比较。

这样的事情:

accounts = [ Account.create(...), Account.create(...) ]
expected_response = accounts.as_json
expect(response.body).to eq(expected_response)