1

所以我在没有测试的情况下制作了我的第一个 Rails 应用程序。现在我正在重做应用程序并首先进行测试。我正在为我正在创建的模型(任务)制定请求规范。我正在测试用于创建新任务的表单。

任务数应该改变 1(即保存了一个新任务),但它没有改变。我基本上遵循了 Michael Hartl 的代码。

Error:
1) Task Pages Creating a Task with valid information creates a Task
   Failure/Error: expect { click_button "Create task" }.to change(Task, :count).by(1)
   count should have been changed by 1, but was changed by 0
# ./spec/requests/tasks_pages_spec.rb:22:in `block (4 levels) in <top (required)>'

相关代码:型号

class Task < ActiveRecord::Base
  attr_accessible :begin_time, :day, :end_time, :gear, :notes, :preset, :room, :setup,                  
  :strike

  validates :room, presence: true
  validates :begin_time, presence: true
  validates :end_time, presence: true
  validates :gear, presence: true
  validates :day, presence: true
end

控制器

def new
  @task = Task.new
end

def create
  @task = Task.new(params[:task])

  if @task.save
    redirect_to root_path
  else
    render 'new'
  end
end

集成测试

require 'spec_helper'

describe "Task Pages" do

  subject { page }

  describe "Creating a Task" do

    let(:submit) { "Create task" }
    before { visit new_task_path }

    describe "with valid information" do 
      before do 
        fill_in "Day",    with: Date.today
        fill_in "Room",   with: "6W-002"
        fill_in "Begin",  with: Time.now
        fill_in "End",    with: 1.hour.from_now
        fill_in "Gear",   with: "LCD"
      end

      it "creates a Task" do 
        expect { click_button "Create task" }.to change(Task, :count).by(1)
      end

    end
  end
end

和形式

<%= form_for(@task) do |t| %>

  <%= t.label :day %>
  <%= t.text_field :day %>

  <%= t.label :room %>
  <%= t.text_field :room %> 

  <%= t.label :begin_time, "Begin" %>
  <%= t.text_field :begin_time %> 

  <%= t.label :end_time, "End" %>
  <%= t.text_field :end_time %> 

  <%= t.label :gear %>
  <%= t.text_field :gear  %> 

  <%= t.label :day %>
  <%= t.text_field :day %> 

  <%= t.submit "Create task", class: "btn btn-large btn-primary" %>
<% end %>
4

1 回答 1

2

您的表单有:day两次该字段。第一个可能由您的测试填充,然后被第二个中的空值破坏。

于 2012-10-14T21:22:14.587 回答