【问题标题】:How to test my devise code using rspec?如何使用 rspec 测试我的设计代码?
【发布时间】:2018-02-14 04:10:07
【问题描述】:

这是我的设计单元测试代码。有什么方法可以写出更好的测试代码吗?

user_spec.rb:

require 'rails_helper'

    RSpec.describe User, type: :model do

      it { should have_many(:companies) }
      it { should have_many(:jobs) }
      it do
               should validate_length_of(:encrypted_password).
                   is_at_least(6).
                   on(:create)
               end

      it { is_expected.to validate_presence_of(:email) }
      it { is_expected.to validate_presence_of(:encrypted_password) }
      it { should have_db_column(:id) }
      it { should have_db_column(:email) }
      it { should have_db_column(:encrypted_password) }
      it { should have_db_column(:confirmation_token) }
      it { should have_db_column(:confirmed_at) }
      it { should have_db_column(:confirmation_sent_at) }

      it 'is databse authenticable' do
        user = User.create(
           email: 'test@example.com', 
          password: 'password123',
          password_confirmation: 'password123'
        )
        expect(user.valid_password?('password123')).to be_truthy
      end
end

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 rubygems


    【解决方案1】:

    好的——据我了解,您是在询问测试 Rails 模型的最佳实践。它是由 Devise 自动生成的这一事实在很大程度上是无关紧要的。

    我在这里要考虑的第一件事是你实际上在测试什么——你这里的大部分代码都是在测试 Devise 的底层实现。这不应该是你的应用程序测试套件的责任——库有一堆测试应该为你测试。

    IMO,这里唯一真正有用的测试是关联测试(看起来它们来自shoulda-matchers)。此处的其他断言是测试特定于 Devise 的代码,它将您的测试套件与第 3 方库紧密耦合——这只会让您陷入更痛苦的世界。

    【讨论】:

    • 非常感谢,这是我写的第一个测试代码。我如何编写更好的单元测试场景。你能给我一个使用设计(用户)的示例测试场景
    • 对于特定于 RSpec 的内容,请查看 Better Specs。有关单元测试的一般指导,请从了解 Arrange Act Assert 开始——它是编写良好测试的基础。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-03
    • 1970-01-01
    相关资源
    最近更新 更多