简体   繁体   English

如何使用rspec测试我的设计代码?

[英]How to test my devise code using rspec?

Here is my unit testing code for devise. 这是我设计的单元测试代码。 Are there any ways to write better test code? 有什么方法可以编写更好的测试代码?

user_spec.rb: 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

Okay – as I understand it you're asking for what the best practices are for testing a Rails model. 好的-据我了解,您正在询问测试Rails模型的最佳实践。 The fact that it's auto-generated by Devise is largely irrelevant. 它是由Devise自动生成的,这一事实在很大程度上是无关紧要的。

The first thing I would consider here is what it is that you're actually testing – most of your code here is testing the underlying implementation of Devise. 我认为这里的第一件事情就是这样 ,你实际测试-大部分代码这里测试设计的底层实现。 That shouldn't be the responsibility of your application's test suite – the library has a bunch of tests that should test that for you. 那不应该由您的应用程序的测试套件负责–库中有很多测试可以为您进行测试。

The only real useful tests here, IMO, are the association tests (which look like they come from shoulda-matchers ). 唯一真正有用的测试是IMO,它是关联测试(看起来像来自应当shoulda-matchers )。 The rest of the assertions here are testing Devise-specific code, which is tightly coupling your test suite to a 3rd-party library – that's only going to put you in a world of pain further down the line. 其余的断言是测试特定于Devise的代码,该代码将您的测试套件与第三方库紧密结合在一起–但这只会使您陷入痛苦之中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM