Rails 测试不使用视图中的模型方法
Rails test not working with model methods in views
使用 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,但我仍然遇到这个问题。我曾尝试对具有不同模型方法的不同页面进行测试,但它们都因相同的错误而失败。
问题是我没有保存更新后的项目。我需要使用@project.update。有一个奇怪的行为,当我更新 owner_id 时,slug 也无缘无故地更新了,但我通过创建一个新项目而不是使用固定装置来解决它。
使用 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,但我仍然遇到这个问题。我曾尝试对具有不同模型方法的不同页面进行测试,但它们都因相同的错误而失败。
问题是我没有保存更新后的项目。我需要使用@project.update。有一个奇怪的行为,当我更新 owner_id 时,slug 也无缘无故地更新了,但我通过创建一个新项目而不是使用固定装置来解决它。