0

我正在编写一个用于练习的小型 Rails 待办事项应用程序。我正在尝试为各种事情编写自己的 Rspec 测试,而不仅仅是遵循教程。我只有几个测试,但有几个失败了,我不知道为什么。我尝试在这里发布问题作为最后的手段,但每次我在这里提出问题时,我都得到了解决问题的好方法。

这是一些代码:

require 'spec_helper'

describe "TodosPages" do
  describe "home page" do
before { visit root_path }

it "should have the content 'Todo App'" do      
    page.should have_content('Todo App')
end  
it "should have title tag" do       
    page.should have_selector 'title'
end  
  it "should delete a todo and redirect to index" do    
      expect { click_link "Delete last todo" }.to change(Todo, :count).by(-1)
      response.should redirect_to :action => 'index'
  end
 describe "Add Todo" do
  subject { page }
   before {click_button "Add todo"}
   it { should have_selector('div.alert.alert-success', text: 'Todo Successfully Created') }

  end

  it "should have a error message" do
    pending
  end

  it "should create a Todo" do
   expect { click_button "Add todo" }.to change(Todo, :count).by(1)
  end


 end

end

 todos_controller



  class TodosController < ApplicationController
  def index
    @todo_items = Todo.all
    @new_todo = Todo.new
    render :index

  end

  def delete
    @todo_delete = Todo.last
    @todo_delete.delete
    redirect_to :action => 'index'

  end

   def add
   todo = Todo.create(:todo_item => params[:todo][:todo_item])
   unless todo.valid?
     flash[:error] = todo.errors.full_messages.join("<br>").html_safe
   else
     flash[:success] = "Todo Successfully Created"  
   end
  redirect_to :action => 'index'
end

def complete
    params[:todos_checkbox].each do |check|
       todo_id = check
       t = Todo.find_by_id(todo_id)
       t.update_attribute(:completed, true)
     end
     redirect_to :action => 'index'
    end
  end

   index.html.erb

<% @title = "Todo App" %>
<div class="container"> 
    <div class="row">
     <div class='span6' >

      <h1 class="hero-unit">Simple Todo App</h1>


      <p>All your todos here</p>
            <%= form_for @new_todo, :url => { :action => "add" }  do |f|  %>
            <%= f.text_field  :todo_item %>
            <%= f.submit "Add todo", class: "btn btn-primary" %>
         <%end%>

            <% if flash[:error] %>
             <div class="alert alert-error">
                <button type="button" class="close" data-dismiss="alert" >×</button>
                <strong><%= flash[:error] %></strong>
                </div>
            <% end %>

            <% if flash[:success] %>
           <div class="alert alert-success">
             <button type="button" class="close" data-dismiss="alert" >×</button>
                <strong><%= flash[:success] %></strong>
           </div>
      <% end %>

<div class="well">
    <%= form_tag("/todos/complete/", :method => "post") do %>
        <ul style="list-style-type:none;">
        <% @todo_items.each do |t| %> 
         <% if t.completed == true %>
         <li style="color:grey;"> <%= check_box_tag  "todos_checkbox[]",t.id %>  <strike><%= t.todo_item %></strike> </li>
      <% else %>
         <li> <%= check_box_tag  "todos_checkbox[]",t.id %> <%= t.todo_item %> </li>
      <% end %>
            <%end%>
            </ul>
                <%= submit_tag("Complete Todos", :class=>"btn btn-success") %>
            <%end %>
        </div> <!-- well --> 
        <%=  link_to "Delete last todo", delete_path %>

    </div> <!-- span6--> 
 </div> <!-- row --> 

  Failures:

 1) TodosPages home page should create a Todo
 Failure/Error: expect { click_button "Add todo" }.to change(Todo, :count).by(1)
   count should have been changed by 1, but was changed by 0
 # ./spec/views/index_page_spec.rb:29:in `block (3 levels) in <top (required)>'

 2) TodosPages home page should delete a todo and redirect to index
 Failure/Error: expect { click_link "Delete last todo" }.to change(Todo, :count).by(-1)
 NoMethodError:
   undefined method `delete' for nil:NilClass
 # ./app/controllers/todos_controller.rb:11:in `delete'
 # (eval):2:in `click_link'
 # ./spec/views/index_page_spec.rb:14:in `block (4 levels) in <top (required)>'
 # ./spec/views/index_page_spec.rb:14:in `block (3 levels) in <top (required)>'

 3) TodosPages home page Add Todo 
 Failure/Error: it { should have_selector('div.alert.alert-success', text: 'Todo Successfully   Created') }
   expected css "div.alert.alert-success" with text "Todo Successfully Created" to return something
 # ./spec/views/index_page_spec.rb:20:in `block (4 levels) in <top (required)>'

 Finished in 0.33114 seconds
 8 examples, 3 failures, 1 pending

 Failed examples:

 rspec ./spec/views/index_page_spec.rb:28 # TodosPages home page should create a Todo
 rspec ./spec/views/index_page_spec.rb:13 # TodosPages home page should delete a todo and redirect to index
 rspec ./spec/views/index_page_spec.rb:20 # TodosPages home page Add Todo 

 Randomized with seed 32260

提前致谢!

------Todo.rb


 class Todo < ActiveRecord::Base
    attr_accessible :todo_item, :completed
    validates :todo_item, presence: true , length: { maximum: 25 }

    end
4

1 回答 1

1

我会试一试。没有特别的顺序:

测试 2(TodosPages 主页应该删除一个待办事项并重定向到索引)

看起来你的 Todo 表在你的测试数据库中是空的,所以当你在控制器操作中调用 Todo.last 时,你会得到 nil,然后尝试在 nil 上调用 delete。

我在您的测试中看不到您在删除测试之前至少创建了一个 Todo 对象的任何地方。

另外,在您的控制器中,您可能需要考虑使用destroy 而不是delete 方法。

测试 1(TodosPages 主页应该创建一个 Todo)

在验证方面,您的 Todo 模型中有哪些内容?是否有任何必填字段?我猜 :todo_item 是必填字段,但是在您的 rspec 测试中,您只需单击按钮并且不为该字段提供任何输入,因此它可能无法通过模型验证。

在添加的控制器操作中,使用 create!而不是创建,如果模型验证失败,它应该会给你额外的错误消息。

测试 3(TodosPages 主页添加 Todo )

可能与上述测试失败的原因相同,即验证失败。首先修复它,然后查看此测试是否通过。

希望这可以帮助。

编辑:通过参数的测试示例

我个人的偏好是将控制器测试(测试特定的控制器功能)与集成类型测试(确保页面正确填充,按钮出现并且可点击等)分开。对于后者,我喜欢使用 Cucumber。然后你可以使用 Rspec 编写一些更简单的控制器测试,它允许你测试特定的逻辑以及将参数直接传递给你正在测试的动作。测试看起来像

describe "add Todo" do
 it "increases count by 1" do 
  expect {post: :add, todo_item: "string"}.to change(Todo, :count).by(1)
 end
end

或者,如果您想继续在 Rspec 中进行集成测试(假设您使用 Capybara 来模拟浏览器),那么您需要为您的 todo_item 文本字段提供一个唯一的 id 或名称,您可以这样做:

it "should create a Todo" do
 fill_in "*todo_item_unique_id" with "some text"
 expect { click_button "Add todo" }.to change(Todo, :count).by(1)
end
于 2013-02-14T04:58:55.517 回答