欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

rspec controller测试 博客分类: 【tec】rails测试 renderresponserspec 

程序员文章站 2024-02-22 19:05:34
...
1 对于controller render/redirect的测试,一般对应以下的测试方法

render :action => :index
response.should render_template('index')

render :partial => 'post'
response.should render_template('_post')

redirect_to login_path
response.should redirect_to(login_path)
但是对于render :nothing = true来说,并没有相应的方法来测试,也无法用render_template来解决,只能是判断返回的response的内容是不是为空了。

response.should have_text(' ')
注意是 ,不是,至于为什么有个空格?我也没有仔细研究

response.body.should =~ /Listing widgets/m
response.body.should eq("")

2 对于controller with invalid params的测试,一般对应以下的测试方法
Member.any_instance.stub(:delete).and_return(false)
3 控制器中方法的调用
subject.send(:log_in,@user)


----------------------------------------实例-----------------------------
1 控制器中的 before_filter 
class MyController < ApplicationController
  before_filter :logged_in?

  def index
  end
end



describe MyController do
  describe "GET 'index'" do
    context "when not logged in"
      # you want to be sure that before_filter is executed
      it "requires authentication" do
        controller.expects :logged_in?
        get 'index'
      end
      # you don't want to spec that it will redirect you to login_path
      # because that spec belongs to #logged_in? method specs
    end
    context "when authenticated" do
      before(:each) { controller.stubs :logged_in? }
      it "renders :index template" do
        get 'index'
        should render_template(:index)
      end
      it "spec other things your action does when user is logged in"
    end
  end
end