ruby-on-rails – 渲染的Rspec测试模板

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 渲染的Rspec测试模板前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图测试成功注册成功模板的条件,由以下控制器代码呈现
def create
    @user = User.new(params[:user])
    if @user.save
      render :template => "success"
    else
      flash[:notice] = "Oops Somethings not quite right! :("
      render :action => "new"
    end
  end

我使用以下规范来测试这个代码

before(:each) do
    @user = User.new
    @user.attributes = valid_attributes    
    @params = valid_attributes
    @user.stub!(:save).and_return(true)
  end


  def do_post
    post :create
  end


  it "should create new user " do
    count = User.count
    do_post
    user = User.new(@params)    
    user.save.should eql(true)
    User.count.should eql(count + 1)

  end

  it "should render the success page on successful signup" do
    do_post
    @user.save
    response.should render_template("success") if @user.save
  end

但是,该示例失败“它应该成功注册成功页面”与此错误消息

1)
'UsersController handling POST /users should render the success page on successful signup' Failed
expected "success",got "users/new.html.erb"
./spec/controllers/users_controller_spec.rb:67:

成功视图是存储在views / users /中没有操作的模板.我猜想我犯了一个非常根本的错误,并希望得到一些帮助.

解决方法

您在测试中存储@user变量,但控制器将实例化一个新实例,因此存根不会到位.

在这种情况下使用存根不仅仅是为了模拟成功的保存调用不是一个好主意.为什么不提供有效数据,并确保操作成功?

以下代码用于RSpec> 2.1它使用expect语法.

before(:each) do
  @params = valid_attributes
end

it "should create new user" do
  @_before = User.count
  post :create,:user => @params

  expect(assigns(:user)).to_not be_new_record
  expect(User.count).to eq(@_before + 1)
end

it "should render the success page on successful signup" do
  post :create,:user => @params

  expect(response).to be_successful
  expect(response).to render_template("success")
end

最后,改变

render :template => "success"

render :action => "success"

对于以前的RSpec版本,或者如果您必须使用应用程序语法,请使用

before(:each) do
  @params = valid_attributes
end

it "should create new user" do
  @_before = User.count
  post :create,:user => @params

  assigns(:user).should_not be_new_record
  User.count.should == (@_before + 1)
end

it "should render the success page on successful signup" do
  post :create,:user => @params

  response.should be_successful
  response.should render_template("success")
end

猜你在找的Ruby相关文章