0

嗨,我正在尝试学习测试和 TDD,所以我开始了一个新项目并制作了一个User模型。我做了一个User模型:name, gender, age

class User < ActiveRecord::Base
  attr_accessible :age, :gender, :name
end

我读到 TDD 是关于进行测试(失败),修复它们,然后再次运行测试以查看它们通过。那么这是否意味着我想要先失败或错误或做任何工作?

我问是因为我刚刚写了第二个测试:

require 'test_helper'

class UserTest < ActiveSupport::TestCase
  test "user is created" do
    user = User.create(:name => "Edmund", :age => 3, :gender => "m")
    assert_equal user, User.find_by_name("Edmund")
    assert_equal 3, User.count
  end

  test "user has sent messages" do
    user = User.create(:name => "Edmund", :age => 3, :gender => "m")
    2.times do 
      user.sent_messages.create(:sender_id => user.id)
    end
    assert_equal 2, user.sent_messages.count
  end


end

对于已发送的消息。我跑了rake test:units,期待它失败,因为我的Message模型中没有任何模型,也没有任何关联,但是has_many :messagesUser得到了一个错误:

Edmunds-MacBook-Pro:langoexchange edmundmai$ rake test:units
NOTICE:  CREATE TABLE will create implicit sequence "users_id_seq" for serial column "users.id"
NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "users_pkey" for table "users"
Run options: 

# Running tests:

E.

Finished tests in 0.087926s, 22.7464 tests/s, 22.7464 assertions/s.

  1) Error:
test_user_has_sent_messages(UserTest):
NoMethodError: undefined method `sent_messages' for #<User:0x007fa73bbd68e0>
    /Users/edmundmai/.rvm/gems/ruby-1.9.3-p194@rails3tutorial2ndEd/gems/activemodel-3.2.8/lib/active_model/attribute_methods.rb:407:in `method_missing'
    /Users/edmundmai/.rvm/gems/ruby-1.9.3-p194@rails3tutorial2ndEd/gems/activerecord-3.2.8/lib/active_record/attribute_methods.rb:149:in `method_missing'
    /Users/edmundmai/Desktop/Class/Ruby/langoexchange/test/unit/user_test.rb:13:in `block (2 levels) in <class:UserTest>'
    /Users/edmundmai/Desktop/Class/Ruby/langoexchange/test/unit/user_test.rb:12:in `times'
    /Users/edmundmai/Desktop/Class/Ruby/langoexchange/test/unit/user_test.rb:12:in `block in <class:UserTest>'

2 tests, 2 assertions, 0 failures, 1 errors, 0 skips
rake aborted!
Command failed with status (1): [ruby -I"lib:test" -I"/Users/edmundmai/.rvm/gems/ruby-1.9.3-p194@rails3tutorial2ndEd/gems/rake-10.0.2/lib" "/Users/edmundmai/.rvm/gems/ruby-1.9.3-p194@rails3tutorial2ndEd/gems/rake-10.0.2/lib/rake/rake_test_loader.rb" "test/unit/**/*_test.rb" ]
Tasks: TOP => test:units
(See full trace by running task with --trace)

这是(错误)TDD 的预期结果还是我做错了什么或错误地解释了 TDD 的过程?

4

2 回答 2

3

是的,这是 TDD 中预期的第一步。一旦你编写了你的​​第一个测试,你的下一个任务就是让你的代码达到实际失败而不是错误的程度。失败与错误不同,因为它意味着您的测试期待某事,而该期待没有得到满足。在发生错误的情况下,期望甚至没有机会被测试,因为被测代码中出现了问题。(在您的情况下,规范永远没有机会检查是否user.sent_messages.count等于,2因为sent_messages甚至没有定义。)

TDD 循环通常侧重于从红色(失败)到绿色(成功 + 重构),因为这是过程的重要部分,但在此循环中隐含的是从错误(未定义的变量/方法等)到实际的过程失败(未达到预期等) 通常,从错误到失败的第一步是相当简单的(在这种情况下,定义一个调用的方法sent_messages,其中没有任何内容来启动,然后再次运行测试),但它可能不是取决于上下文。

于 2012-12-04T04:19:36.773 回答
0

是的,你的测试最初应该失败(否则,没有工作要做),然后你做最少的事情让它通过。每隔一段时间(我在做 TDD 时每 20 个测试做一次),你就重构它们。

于 2012-12-04T04:19:19.857 回答