这可能在控制器测试中吗?

Is this possible in controller test?

在我的用户控制器中,我有一个用于新 page/method 的 before_action。这个before_action包括:

@organization = Organization.friendly.find(params[:id])

在我的用户装置中,我有一个用户@admin 的 organization: one,在我的组织装置中,我有这个组织的记录 "one"。我的控制器测试仍然在上面的行中失败并显示消息:

ActiveRecord::RecordNotFound: Couldn't find Organization without an ID

这是为什么?是否无法在控制器测试中执行此操作,我应该改用集成测试吗?如果我可以使用控制器测试(我在这里更喜欢),我的代码有什么问题?


控制器测试:

  test "should get new" do
    log_in_as("user", @admin) # Test helper that functions properly
    get :new                  # It fails here on the before_action defined in the users controller.
    assert_response :success
  end

你期望有params[:id],但你没有通过。尝试

test "should get new" do
  log_in_as("user", @admin)
  get :new, id: 1 # or any other
  assert_response :success
end

您需要更改 before_action 过滤器或更新测试。

根据您显示的信息,我认为问题在于您应该限制之前的操作。 例如 before_action :set_organization, except:[:index,:new] 或仅使用 before_action :set_organization, only:[:show,:edit,:update,:destroy].

如果要为所有操作设置组织,则应提供 id 参数。

例如:

  before_action :set_organization

  def set_organization
     @organization = Organization.friendly.find(params[:organization_id])
  end


  get :new,organization_id: 1