如何使用RSpec检查JSON响应? [英] How to check for a JSON response using RSpec?
问题描述
我的控制器中包含以下代码:
I have the following code in my controller:
format.json { render :json => {
:flashcard => @flashcard,
:lesson => @lesson,
:success => true
}
在我的RSpec控制器测试中,我想验证某个方案确实收到了成功的json响应,所以我有以下一行:
In my RSpec controller test I want to verify that a certain scenario does receive a success json response so I had the following line:
controller.should_receive(:render).with(hash_including(:success => true))
尽管我运行测试时遇到以下错误:
Although when I run my tests I get the following error:
Failure/Error: controller.should_receive(:render).with(hash_including(:success => false))
(#<AnnoController:0x00000002de0560>).render(hash_including(:success=>false))
expected: 1 time
received: 0 times
我是否正确检查了响应?
Am I checking the response incorrectly?
推荐答案
您可以检查响应对象并验证其是否包含期望值:
You can examine the response object and verify that it contains the expected value:
@expected = {
:flashcard => @flashcard,
:lesson => @lesson,
:success => true
}.to_json
get :action # replace with action name / params as necessary
response.body.should == @expected
编辑
将其更改为post
会使它变得有些棘手.这是一种处理方法:
Changing this to a post
makes it a bit trickier. Here's a way to handle it:
it "responds with JSON" do
my_model = stub_model(MyModel,:save=>true)
MyModel.stub(:new).with({'these' => 'params'}) { my_model }
post :create, :my_model => {'these' => 'params'}, :format => :json
response.body.should == my_model.to_json
end
请注意,mock_model
不会响应to_json
,因此需要stub_model
或真实模型实例.
Note that mock_model
will not respond to to_json
, so either stub_model
or a real model instance is needed.
这篇关于如何使用RSpec检查JSON响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!