首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用MiniTest进行模型测试?

使用MiniTest进行模型测试?
EN

Stack Overflow用户
提问于 2013-03-06 00:07:54
回答 1查看 860关注 0票数 1

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

代码语言:javascript
复制
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为空,它将创建一个新的auth

我是用if子句写的,但我不知道它是真是假。我怎样才能纠正这个测试?

EN

回答 1

Stack Overflow用户

发布于 2013-03-06 00:36:05

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

让我们假设您有以下代码:

代码语言:javascript
复制
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中有以下fixture数据

代码语言:javascript
复制
test_auth:
  provider: twitter
  uid: abc123
  user: test_user

我会有一个类似于下面的测试:

代码语言:javascript
复制
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

顺便说一下,我不喜欢这个方法的名字。名称类似于动态查找器,但行为不同。我会将该方法重命名为for_provider_and_uid

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15228582

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档