【问题标题】:Failing Test in Rails with Minitest: Why is my seed not working? Why does it work if I use fixtures instead?使用 Minitest 在 Rails 中测试失败:为什么我的种子不起作用?如果我改用固定装置,为什么它会起作用?
【发布时间】:2020-09-01 17:03:19
【问题描述】:

我已经开始学习如何使用 Ministest 进行测试。我有一个用于运行测试的辅助项目。

我正在运行一个简单的测试,其中用户登录、访问项目索引并尝试创建一个新项目。

我通过控制台播种:

rake db:seed RAILS_ENV=test

索引处有一个模式窗口,要求用户将“技术”添加到他的“技能组”中。我正在使测试关闭模式,以便它可以像这样单击“创建项目”按钮:

  test "a logged in user can create a project" do
    login_as users(:admin)
    visit projects_url
    click_on "Later" // close modal window
    click_on "Create Project"
    assert_equal new_project_path, page.current_path
  end

但是,我收到了与模式窗口本身相关的错误,因为 Technology.first 等为 nil。就好像种子没有运行并填充数据库一样。

使用技术实例的模态:

<div class="modal-body">
    <p class="mr-3 mb-0" style="font-size: 1.4rem; text-align: center;">
       <%= link_to (sanitize pick_tech_icon(Technology.first.name), tags: %w(i), attributes: %w(class style)) %>
       <%= link_to (sanitize pick_tech_icon(Technology.second.name), tags: %w(i), attributes: %w(class style)) %>
       <%= link_to (sanitize pick_tech_icon(Technology.third.name), tags: %w(i), attributes: %w(class style)) %>
       <%= link_to (sanitize pick_tech_icon(Technology.fourth.name), tags: %w(i), attributes: %w(class style)) %>
       <%= link_to (sanitize pick_tech_icon(Technology.fifth.name), tags: %w(i), attributes: %w(class style)) %>
    </p>
</div>

控制台错误:

Error:
ProjectsTest#test_a_logged_in_user_can_create_a_project:
ActionView::Template::Error: undefined method `name' for nil:NilClass
    app/views/shared/_add_skill_modal.html.erb:13
    app/views/projects/index.html.erb:1

为什么我的种子不起作用?如果我使用技术夹具来创建技术实例,为什么测试运行正常?我认为fixture不应该替换数据库数据,而是作为测试数据。

【问题讨论】:

    标签: ruby-on-rails database testing fixtures


    【解决方案1】:

    在 Rails 4.x 中,我们有事务性固定装置,它们将每个测试包装在一个 数据库事务。此事务回滚所有更改 测试结束。它表示数据库的状态,在 测试与测试完成后相同。

    默认情况下启用此功能。我们可以选择禁用它 通过设置类属性在测试用例类中 使用_transactional_fixtures 为假

    然而,

    为了克服这种混淆,Rails 5 有 renamed transactional fixtures to transactional tests 明确表示它与测试中使用的固定装置无关。

    参考:https://blog.bigbinary.com/2016/05/26/rails-5-renamed-transactional-fixtures-to-transactional-tests.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-04
      • 1970-01-01
      • 2013-03-21
      相关资源
      最近更新 更多