如何为返回对象的方法编写控制器规范,但不检查任何相关模板

时间:2019-07-04 14:29:14

标签: ruby-on-rails ruby rspec-rails rspec3

我想通过基本示例以更简洁的方式问我的问题。

1) I have UsersController
2) I have show method in it
3) But I don't have any templates for this method(either - show.html.erb/show.xml.erb etc)
4) So currently, I just wanted to write a spec for just checking whether my method is returning an object or not
5) it is working, but as it is CRUD related method, it is expecting a Template for it.
6) ActionView::MissingTemplate

我已经尝试过这种方式

it "should show the user record" do
  get :show, :id => 1
  User.should_receive(:find).at_least(:once).with(1).and_return(mock_user)
end
class UsersController
  def show
    # params = {}
    # params = {:id => 1}
    @user_obj = User.find(params[:id]) # ActiveRecord::Relation
  end
end

require 'spec_helper'

describe UsersController do
  def mock_user(stubs={})
    @mock_user ||= mock_model(User, stubs).as_null_object
  end

  it "should show the user record" do
    expect(assigns(:user_obj)).to eq(mock_user) # How to stop execution  here only.
  end
end
  

ActionView :: MissingTemplate:缺少模板用户/显示为   {:handlers => [:erb,:rjs,:builder,:rhtml,:rxml] 、: formats => [:html],   :locale => [:en,:en]}在视图路径中   “#”

2 个答案:

答案 0 :(得分:0)

您尝试做的事情对我来说似乎不合适。 这种测试(控制器测试)用于测试动作和渲染的响应。因此您不应该测试动作渲染的输出。否则,如果您只想测试方法show(单元测试) 不要在这里使用get

users_controller = UsersController.new
users_controller.show 

并将其作为任何类中的任何方法进行测试

答案 1 :(得分:0)

您缺少渲染器,因此它会搜索要渲染的模板。

class UsersController
  def show
    # params = {}
    # params = {:id => 1}
    @user_obj = User.find(params[:id])
    render status: 200, json: @user_obj
  end
end

现在您的规格应该工作。