【问题标题】:Rails test not working with model methods in viewsRails 测试不适用于视图中的模型方法
【发布时间】:2020-12-17 02:48:20
【问题描述】:

使用 Rails 进行测试时,在视图中调用模型方法不起作用。是否有一个原因?在浏览器中访问页面时,这些功能都可以正常工作。

导致问题的视图线:

<%= f.select :user_id, options_for_select(@project.assignment_options(current_user)),
            { include_blank: "Teammate to assign" }, class: "uk-select uk-margin-small-right" %>

测试:

  def current_user
    @user
  end
  
  setup do
    @user = users(:one)
    sign_in @user
    @project = projects(:one)
    @project.owner_id = @user.id
    @assignment = assignments(:one)
  end

  test "should get new" do
    get new_project_assignment_url(@project.slug)
    assert_response :success
  end

错误:

E

Error:
AssignmentsControllerTest#test_should_get_new:
ActionView::Template::Error: Couldn't find User without an ID
    app/models/project.rb:33:in `owner'
    app/models/project.rb:63:in `assignment_options'
    app/views/assignments/_form.html.erb:6
    app/views/assignments/_form.html.erb:2
    app/views/assignments/new.html.erb:2
    test/controllers/assignments_controller_test.rb:18:in `block in <class:AssignmentsControllerTest>'

当我从视图中执行“puts current_user.id”并测试它们是否匹配时,页面上肯定有可用的用户 ID,但我仍然遇到这个问题。我尝试对具有不同模型方法的不同页面进行测试,但它们都失败并出现相同的错误。

【问题讨论】:

    标签: ruby-on-rails integration-testing


    【解决方案1】:

    问题是我没有保存更新的项目。我需要使用@project.update。有一个奇怪的行为,当我更新 owner_id 时,slug 也无缘无故地更新了,但我只是通过创建一个新项目而不是使用夹具来解决它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-04
      • 1970-01-01
      相关资源
      最近更新 更多