1

我正在使用 MiniTest 框架,并想编写一个模型测试。这是我的测试代码:

it "must find or create authentication" do
  auth = Authentication.find_by_provider_and_uid( @auth.provider,
  @auth.uid )
  val = auth.nil?
  if val==true
    Authentication.create_with_omniauth @auth
  end
end

此测试检查该Authentication.find_by_provider_and_uid方法是否存在,如果auth为 nil,它将创建一个新的auth.

我用一个if从句写的,但我不知道它是否正确。我怎样才能纠正这个测试?

4

1 回答 1

1

因为您的问题中没有代码,所以我假设您正在使用minitest-rails并对其进行了正确配置,因为这是我最熟悉的。

假设您有以下代码:

class Authentication < ActiveRecord::Base
  def self.find_by_provider_and_uid provider, uid
    self.where(provider: provider, uid: uid).first_or_initalize
  end
end

此外,我会假设你有以下夹具数据test/fixtures/authentications.yml

test_auth:
  provider: twitter
  uid: abc123
  user: test_user

我将进行类似于以下的测试:

describe Authentication do

  describe "find_by_provider_and_uid" do

    it "retrieves existing authentication records" do
      existing_auth = authentications :test_auth
      found_auth = Authentication.find_by_provider_and_uid existing_auth.provider, existing_auth.uid
      refute_nil found_auth, "It should return an object"
      assert found_auth.persisted?, "The record should have existed previously"
      assert_equal existing_auth, found_auth
    end

    it "creates a new authentication of one doesn't exist" do
      new_auth = Authentication.find_by_provider_and_uid "twitter", "IDONTEXIST"
      refute_nil new_auth, "It should return an object"
      assert new_auth.new_record?, "The record should not have existed previously"
    end

  end

end

FWIW,我不喜欢这种方法的名称。名称类似于动态查找器,但行为不同。我会将方法重命名为for_provider_and_uid.

于 2013-03-05T16:36:05.197 回答