我有一个令人困惑的问题,我的控制器工作正常。 但是,当我使用RSPEC测试它时,它将返回一个空字符串作为响应主体。
这里是控制器:
class Api::UsersController < Api::ApplicationController def show @user = User.find(params[:id]) render 'show', status: 200 # render json: @user end end我正在渲染的RABL模板:
object @user attributes :id, :name, :email, :phone_number, :invite_token最后这里是我的规格:
require "spec_helper" describe Api::UsersController do it "returns user attributes" do user = FactoryGirl.create(:user, name: "Mark", email: "foo@bar.com") get :show, id: user.id expect(response.status).to eq(200) output = JSON.parse(response.body) end end当我使用render'show'渲染RABL模板时,我的测试失败,因为response.body是一个空字符串。 但是,如果我CURL到该端点,身体回报就好了。
当我将控制器更改为:呈现json:@user时,测试通过。
谁能告诉我这里发生了什么?
提前致谢!
I'm having a perplexing problem where my controller is working fine. However, when I'm testing it with RSPEC it's returning an empty string as the response body.
Here is the controller:
class Api::UsersController < Api::ApplicationController def show @user = User.find(params[:id]) render 'show', status: 200 # render json: @user end endAnd the RABL template I'm rendering:
object @user attributes :id, :name, :email, :phone_number, :invite_tokenFinally here is my spec:
require "spec_helper" describe Api::UsersController do it "returns user attributes" do user = FactoryGirl.create(:user, name: "Mark", email: "foo@bar.com") get :show, id: user.id expect(response.status).to eq(200) output = JSON.parse(response.body) end endWhen I use render 'show' to render the RABL template my test fails as the response.body is an empty string. However, if I CURL to that endpoint, the body returns just fine.
When I change the controller to: render json: @user the test passes.
Can anyone tell me what's going on here?
Thanks in advance!
最满意答案
尝试在测试的顶部添加render_views
describe Api::UsersController do render_views it "returns user attributes" do user = FactoryGirl.create(:user, name: "Mark", email: "foo@bar.com") get :show, id: user.id output = JSON.parse(response.body) expect(response.status).to eq(200) expect(output).to eq(expected_hash) end end可能的原因:RSpec默认情况下不呈现视图来加速测试。
try to add render_views at the top of the tests
describe Api::UsersController do render_views it "returns user attributes" do user = FactoryGirl.create(:user, name: "Mark", email: "foo@bar.com") get :show, id: user.id output = JSON.parse(response.body) expect(response.status).to eq(200) expect(output).to eq(expected_hash) end endPossible reason: RSpec do not render views by default to speed up tests.
更多推荐
发布评论