失败/错误:期望(响应).to render_template(:new)

时间:2014-03-27 05:01:29

标签: ruby ruby-on-rails-4 rspec2

我做错了什么?运行rspec时我不断收到此错误:

  

故障:

     

1)AccountsController POST:创建一个已存在的帐户呈现:new模板        失败/错误:期望(响应).to render_template(:new)          期待<“new”>但使用< []> 进行渲染        #./spec/controllers/accounts_controller_spec.rb:131:in块中的“块(4级)”

     

以0.26832秒结束   34个例子,1个失败

     

失败的例子:

     

rspec ./spec/controllers/accounts_controller_spec.rb:128#AccountsController POST:创建一个已经存在的帐户呈现:新模板

我通过在rails控制台中运行它来验证我的代码是否正确编写。而且确实如此,它呈现:new模板甚至返回200.我通过在rails控制台中使用app对象来实现这一点。输出如下:

Started POST "/accounts" for 127.0.0.1 at 2014-03-26 21:18:06 -0700
Processing by AccountsController#create as HTML
Parameters: {"account"=>{"name"=>"name", "description"=>"desc", "opening_balance"=>"1.0"}}
 (0.1ms)  begin transaction
Account Exists (0.2ms)  SELECT 1 AS one FROM "accounts" WHERE "accounts"."name" = 'name' LIMIT 1
 [deprecated] I18n.enforce_available_locales will default to true in the future. If you really want to skip validation of your locale you can set I18n.enforce_available_locales = false to avoid this message.
 (0.1ms)  rollback transaction
**Rendered accounts/new.html.erb within layouts/application (1.4ms)**
Completed 200 OK in 44ms (Views: 32.8ms | ActiveRecord: 0.3ms)
 => 200

这会创建两次相同的帐户。我希望,它会失败,然后重定向到:新模板。 rspec代码在这里:

  context 'an account that already exists' do

     it 'renders the :new template' do
       call_post_create_verb
       call_post_create_verb
       **expect(response).to render_template(:new)**
     end

   end  

查看else条件,你会找到我渲染的地方:new。控制器代码在这里:

def ceate
   @account = Account.new(account_params)
   if @account.save
     redirect_to @account
   else
     **render :new**
   end
end

这是我的设置: ruby 2.1.1p76(2014-02-24修订版45161)[x86_64-darwin13.0] 铁轨(4.0.3) rspec-rails(2.14.1)

2 个答案:

答案 0 :(得分:1)

let(:call_post_create_verb) { post :create, account: valid_info }

最初模拟两次创建同一个帐户,我只是简单地调用了两次。它应该工作,但它拒绝。因此,我没有将其调用两次,而是将第一个调用更改为:

Account.create valid_info

所以我首先在模型中创建它,然后调用'post create'来创建一个具有相同信息的帐户,这肯定会失败,因为我正在验证name属性中的唯一性。

这样做之后,它终于奏效了。

答案 1 :(得分:0)

我认为您需要在规范中添加render_views。 RSpec默认不提供任何内容 - 这就是为什么你得到"期待<" new">但使用< []>"

进行渲染
context 'an account that already exists' do

  render_views

  it 'renders the :new template' do
    call_post_create_verb
    call_post_create_verb
    **expect(response).to render_template(:new)**
  end

结束

相关问题