【问题标题】:Rspec testing templates being rendered正在呈现的 Rspec 测试模板
【发布时间】:2010-09-28 08:33:37
【问题描述】:

我正在尝试测试以下控制器代码在成功注册时呈现成功模板的条件

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:

成功视图是存储在视图/用户/中的模板,没有操作。我猜我犯了一个非常根本的错误,需要一些帮助。

【问题讨论】:

  • 我会删除你最后一个断言的 user.save 条件。
  • 伙计,你的问题是我的答案。

标签: ruby-on-rails rspec


【解决方案1】:

您在测试中对 @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 版本,或者如果您必须使用 should 语法,请使用

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

【讨论】:

  • 就是这样。我刚得到它。谢谢你。我仍在了解如何使用 Rspec。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-24
  • 1970-01-01
  • 1970-01-01
  • 2011-09-17
  • 1970-01-01
相关资源
最近更新 更多