ruby-on-rails - 在单元测试 Rails 模型中使用 shoulda-matchers 还是 Factory Girl 更好?

标签 ruby-on-rails unit-testing rspec factory-bot shoulda

我正在练习测试(刚刚开始),并且想知道在测试模型中使用 shoulda-matchers 或 Factory Girl - 或两者的组合是否更好。例如,我目前只使用简单的 shoulda-matchers 测试,这是很好且简单的:

RSpec.describe User, :type => :model do
    describe User do
        it { should validate_presence_of(:username) }
        it { should validate_presence_of(:password_decoded) }
        it { should validate_length_of(:password).is_at_least(3) }
        it { should validate_presence_of(:session_token) }
        it { should have_one(:shopping_cart)}
    end
end

但是,根据我的理解,这实际上并没有像 Factory Girl 那样实例化 User 对象。上述内容对于测试来说“足够”了吗?任何想法表示赞赏!

最佳答案

factory_girl 和 Shoulda-matchers 做两件不同的事情。大多数 Rails 应用程序都需要这两件事。这不是非此即彼的问题。事实上,同一个人(Thoughtbot)在这两个 gem 背后是一个很好的线索,表明它们同时有用。

  • factory_girl 允许您创建(仅在内存或数据库中)用于测试的对象。大多数应用程序需要在测试中一遍又一遍地创建类似的对象; factory_girl 消除了这样做的重复。它还允许您轻松自定义预定义对象(例如,比 Rails 夹具更容易)。您显示的模型规范不需要factory_girl,但如果您的模型中有任何比基本配置更复杂的代码,那么使用factory_girl创建要测试的模型可能会有所帮助。

  • shoulda-matchers 可以更轻松地断言您在测试中获得了预期的结果。它提供了 RSpec 匹配器来断言有关模型和 Controller 的事情。大多数应用程序会发现 shoulda-matchers 的 ActiveModel 匹配器对于确保其模型得到良好验证很有用。 (Personally I get more use out of shoulda-matchers' ActiveModel matchers than the ActiveRecord matchers.)

关于ruby-on-rails - 在单元测试 Rails 模型中使用 shoulda-matchers 还是 Factory Girl 更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35414354/

相关文章:

ruby-on-rails - 你如何设置一个 rspec View 规范,以便 render 只为它的所有规范调用一次?

ruby-on-rails - Ruby Object#id 警告和 Active Record

ruby-on-rails - 将 float 格式化为最小小数位数

ruby-on-rails - rails : How does the console decide which Ruby version to use?

ruby-on-rails - 如何在 Rails 的同一个文件中多次运行 rake 任务

mysql - 如何在 Node js 中使用一些模拟数据和 mocha stub mysql 查询

python - 如何将 passenv 添加到 tox.ini 而不编辑文件,而是通过在代理后面的 Jenkins 中的 virtualenv shell nature 脚本中运行 tox (python)

ruby-on-rails - Rails Devise PG::SyntaxError: ERROR: ""处或附近的零长度分隔标识符“”

unit-testing - 在Spock中调用模拟时是否会创建新的返回对象?

ruby-on-rails - 如何防止加载 RSpec 助手