测试渲染的视图

时间:2014-06-29 16:21:26

标签: ruby-on-rails rspec

根据以下代码(taken from here)的代码:

describe WidgetsController do
  describe "index" do
    it "renders the index template" do
      get :index
      expect(response).to render_template("index")
      expect(response.body).to eq ""
    end
    it "renders the widgets/index template" do
      get :index
      expect(response).to render_template("widgets/index")
      expect(response.body).to eq ""
    end
  end
end

似乎我们可以测试某个视图是否已渲染,而不实际呈现视图本身,这是一个很好的单位规格。

然而,它对我不起作用:

subject { response }

describe '#create' do
  context 'with valid params' do
    before do
      post :create, asset: { uploaded_file: file }
    end

    it { should have_http_status 302 }
    it { should redirect_to '/' }
    it { should render_template 'home' }

  end
end

结果:

AssetsController
  #create
    with valid params
      should respond with numeric status code 302
      should redirect to "/"
      should render template matcher "home" (FAILED - 1)

Failures:

  1) AssetsController#create with valid params should render template matcher "home"
     Failure/Error: it { should render_template 'home' }
       expecting <"home"> but rendering with <[]>
     # ./spec/controllers/assets_controller.rb:27:in `block (4 levels) in <top (required)>'

那么如何在不渲染视图的情况下测试视图呢?

1 个答案:

答案 0 :(得分:0)

您的代码正在进行重定向,而不是渲染(由第二个it块证明)

在浏览器中,重定向可能会导致主页模板,但控制器规范一次只处理一个http请求/响应(正如您指出的那样,我们正在尝试对控制器进行单元测试)

如果您想要指定浏览器跟随重定向后会发生什么,那么您需要一个请求规范。