0

我第一次在我的User模型中尝试自己进行测试,我意识到对于每个测试我都有一个针对user = User.create(:name => "something", :age => 3, :gender => "m"). 是否有 before_filter 或类似的测试,这样我就不必为每个测试创建一个用户?或者以某种方式将它放在全局命名空间中,以便在任何地方都可以访问它?

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

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


end
4

1 回答 1

3

是的,您可以为您的测试定义一个设置方法,该方法将在每次测试之前运行。如果您在那里定义一个全局变量,那么它可以在所有测试用例中访问。

前任:

class UserTest < ActiveSupport::TestCase

  setup do
    @user = User.create(:name => "Edmund", :age => 3, :gender => "m")
  end

  test "user has sent messages" do
    2.times do 
      @user.sent_messages.create(:sender_id => user.id)
    end
    assert_equal 2, @user.sent_messages.count
  end

end
于 2012-12-04T20:01:09.273 回答