require "test_helper" class SharesApiTest < ActionDispatch::IntegrationTest include ActionMailer::TestHelper setup do @anna = create_user("anna@example.com") @bob = create_user("bob@example.com") @doc = create_document(@anna) end test "only the owner manages sharing" do DocumentMembership.grant!(document: @doc, user: @bob, role: :editor, source: :invite) sign_in @bob get "/api/documents/#{@doc.id}/share" assert_response :not_found end test "one active link per role; a new one revokes the old" do sign_in @anna post "/api/documents/#{@doc.id}/share/links", params: { role: "editor" }, as: :json first = json["links"].first["token"] post "/api/documents/#{@doc.id}/share/links", params: { role: "editor" }, as: :json assert_equal 1, json["links"].size assert_not_equal first, json["links"].first["token"] assert_nil @doc.role_for(token: first) delete "/api/documents/#{@doc.id}/share/links/#{json['links'].first['id']}" assert_empty json["links"] end test "invite by mail, change role, remove" do sign_in @anna assert_enqueued_emails 1 do post "/api/documents/#{@doc.id}/share/invitations", params: { email: "bob@example.com", role: "viewer" }, as: :json end assert_equal [ "bob@example.com" ], json["invitations"].map { _1["email"] } MagicLink.invitation.last.redeem! get "/api/documents/#{@doc.id}/share" assert_equal [ [ "bob@example.com", "viewer", "invite" ] ], json["members"].map { _1.values_at("email", "role", "source") } assert_empty json["invitations"] patch "/api/documents/#{@doc.id}/share/members/#{@bob.id}", params: { role: "editor" }, as: :json assert_equal :editor, @doc.role_for(user: @bob) delete "/api/documents/#{@doc.id}/share/members/#{@bob.id}" assert_nil @doc.role_for(user: @bob) end test "cannot invite yourself" do sign_in @anna post "/api/documents/#{@doc.id}/share/invitations", params: { email: "anna@example.com", role: "viewer" }, as: :json assert_response :unprocessable_entity end end