【问题标题】:Why is my unit test trying to insert a record when I'm not asking it to?为什么我的单元测试在我不要求时尝试插入记录?
【发布时间】:2018-06-08 09:51:24
【问题描述】:

我正在使用带有设计的 rails 5。我正在尝试为我的控制器编写一些单元测试,但我正在碰壁。这是我正在尝试测试的方法

  # GET /issues/new
  def new
    unless user_signed_in?
      redirect_to new_user_session_path
    end
    @issue = Issue.new(stop_onestop_id: params[:stop_id], line_onestop_id: params[:line_id])
  end

这是我正在编写的测试

# issues_controller_test.rb
class IssuesControllerTest < ActionDispatch::IntegrationTest

  include Devise::Test::IntegrationHelpers

  test "logged in should get issues page" do
    sign_in users(:one)
    test_stop_id = 1
    test_line_id = 1
    get new_issue_url, params: {stop_id: test_stop_id, line_id: test_line_id}
    assert_equal test_stop_id, @issue.stop.id
    assert_equal test_line_id, @issue.line.id
    assert_response :success
  end
end

但是,当我运行它时,我得到以下异常...

localhost:Caravan-App davea$ rails test
Running via Spring preloader in process 9509
Run options: --seed 48437

# Running:

E

Error:
IssuesControllerTest#test_logged_in_should_get_issues_page:
ActiveRecord::RecordNotUnique: SQLite3::ConstraintException: UNIQUE constraint failed: users.email: INSERT INTO "users" ("created_at", "updated_at", "id") VALUES ('2017-12-27 19:07:16.234345', '2017-12-27 19:07:16.234345', 298486374)



bin/rails test test/controllers/issues_controller_test.rb:6



Finished in 0.320746s, 3.1177 runs/s, 0.0000 assertions/s.

1 runs, 0 assertions, 0 failures, 1 errors, 0 skips

我不是在哪里要求创建新记录,那么为什么我的测试试图插入一个?

【问题讨论】:

  • users(:one) 正在抓取一个测试夹具。你检查过你的users.yml 夹具文件吗?你可能有几个灯具违反了独特的电子邮件限制。
  • 尝试将redirect_to new_user_session_path更改为redirect_to new_user_session_path and return
  • @DerekHopper,与 taht 固定装置文件的良好通话。这确实是问题所在。
  • 这不是问题的1/2吗?它似乎根本不应该运行`@issue = Issue.new(stop_onestop_id: params[:stop_id], line_onestop_id: params[:line_id])`,除非user_signed_in?...

标签: ruby-on-rails sqlite unit-testing devise ruby-on-rails-5


【解决方案1】:

sign_in users(:one) 行中,users(:one) 正在获取一个夹具。看到这告诉我你正在使用一个固定文件。

您的项目中有一个文件users.yml,它定义了一些用于测试的用户。看起来ActiveRecord::RecordNotUnique 异常来自那里。更具体地说,用户夹具似乎违反了users.email 的唯一性约束。

如果您通过为每个用户提供一个唯一的电子邮件地址来修复您的 users.yml 文件,那么您应该很高兴。

【讨论】:

    猜你喜欢
    • 2010-09-25
    • 1970-01-01
    • 1970-01-01
    • 2017-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多