且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何对 JSON 控制器进行单元测试?

更新时间:2023-09-28 17:47:34

就像上面评论的那样,这将是一个功能测试.

Just like people commented above, this would be a functional test.

***的方法可能是发出请求、解析 JSON 响应正文并将其与预期结果匹配.

The best way would probably be making a request, parsing the JSON response body, and matching it to the expected result.

如果我使用 FactoryGirl 在 Rspec 中有 companies_controller:

If I have companies_controller in Rspec using FactoryGirl:

describe "GET 'show'" do

  before(:each) do
    @company = Factory(:company)
    get 'show', :format => :json, :id => @company.id
  end

  it "should be successful" do
     response.should be_success
  end

  it "should return the correct company when correct id is passed" do
    body = JSON.parse(response.body)
    body["id"].should == @company.id
  end

end

您可以用同样的方式测试其他属性.另外,我通常有 invalid 上下文,我会在其中尝试传递无效参数.

You can test other attributes the same way. Also, I normally have invalid context where I would try to pass invalid parameters.