如何对 JSON 控制器进行单元测试? [英] How to unit-test a JSON controller?
问题描述
这是我的操作:
def my_action
str = ... # get json str somehow
render :json => str
end
这是我的测试:
test "my test" do
post(:my_action, {'param' => "value"}
assert_response :success
end
我想添加另一个断言,即发出的 JSON 包含一些值.如何在控制器单元测试中执行此操作,而不是通过解析视图结果?
I want to add another assertion that the emitted JSON contains some value. How can I do it in a controller unit-test, not via parsing the view result?
推荐答案
就像上面评论的那样,这将是一个功能测试.
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.
这篇关于如何对 JSON 控制器进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!