diff --git a/.eslint_todo.ts b/.eslint_todo.ts index 0fc1edee8..145dbf3cb 100644 --- a/.eslint_todo.ts +++ b/.eslint_todo.ts @@ -1,30 +1,19 @@ // This configuration was generated by `exe/eslint_autogen` -// on 2026-11-28 02:54:57 UTC. +// on 2026-11-28 04:52:47 UTC. // The point is for the user to remove these configuration records // one by one as the offenses are removed from the code base. import type {Linter} from "eslint"; const config: Linter.Config[] = [ - // Offense count: 2 - { - files: [ - "spec/javascript/helpers/api_spec.ts", - ], - rules: { - "@stylistic/dot-location": "off", - }, - }, - // Offense count: 52 + // Offense count: 36 { files: [ "app/javascript/controllers/mark_all_as_read_controller.ts", "app/javascript/controllers/unread_count_controller.ts", - "app/javascript/helpers/api.ts", "eslint.config.ts", "spec/javascript/controllers/mark_all_as_read_controller_spec.ts", "spec/javascript/controllers/unread_count_controller_spec.ts", - "spec/javascript/helpers/api_spec.ts", "types/eslint-plugin-sort-keys-fix.d.ts", "vitest.config.ts", ], @@ -62,17 +51,6 @@ const config: Linter.Config[] = [ "@stylistic/quote-props": "off", }, }, - // Offense count: 5 - { - files: [ - "app/javascript/controllers/story_controller.ts", - "spec/javascript/controllers/story_controller_spec.ts", - "spec/javascript/helpers/api_spec.ts", - ], - rules: { - "camelcase": "off", - }, - }, // Offense count: 2 { files: [ @@ -91,15 +69,6 @@ const config: Linter.Config[] = [ "max-len": "off", }, }, - // Offense count: 1 - { - files: [ - "spec/javascript/helpers/api_spec.ts", - ], - rules: { - "vitest/no-hooks": "off", - }, - }, ]; export default config; diff --git a/app/components/story.rb b/app/components/story.rb index 6a14af4ad..61a06f436 100644 --- a/app/components/story.rb +++ b/app/components/story.rb @@ -36,7 +36,6 @@ def data def values { - story_id_value: story.id.to_s, story_is_read_value: story.is_read.to_s, story_keep_unread_value: story.keep_unread.to_s } diff --git a/app/components/story_frame.rb b/app/components/story_frame.rb index cb4c7eafe..a5991c53d 100644 --- a/app/components/story_frame.rb +++ b/app/components/story_frame.rb @@ -26,6 +26,7 @@ def initialize(story:) def view_template turbo_frame(id: "story_#{story.id}") do preview + render(Components::StoryMarkRead.new(story:)) div(class: "story-body-container") do story_body render(Components::StoryActions.new(story:)) diff --git a/app/components/story_mark_read.rb b/app/components/story_mark_read.rb new file mode 100644 index 000000000..c70ccf95b --- /dev/null +++ b/app/components/story_mark_read.rb @@ -0,0 +1,24 @@ +# frozen_string_literal: true + +# A form with no visible fields that the story controller submits when the +# story opens. The response is a Turbo Stream that replaces the keep unread +# form, whose saved state then marks the story read (see +# `Components::StoryKeepUnread`). +class Components::StoryMarkRead < Components::Base + attr_accessor :story + + def initialize(story:) + super() + self.story = story + end + + # The empty block matters: without one, form_with leaves the form open. + def view_template + form_with( + url: "/stories/#{story.id}/read", + method: :patch, + class: "story-mark-read-form", + data: { story_target: "markRead" } + ) { nil } + end +end diff --git a/app/controllers/stories_controller.rb b/app/controllers/stories_controller.rb index d1b7df2ff..a1c1aea48 100644 --- a/app/controllers/stories_controller.rb +++ b/app/controllers/stories_controller.rb @@ -14,15 +14,6 @@ def index render(Views::Stories::Index.new(stories:)) end - def update - json_params = JSON.parse(request.body.read, symbolize_names: true) - - story = authorization.check(StoryRepository.fetch(params[:id])) - story.update!(json_params.slice(:is_read, :is_starred, :keep_unread)) - - head(:no_content) - end - def refresh story = authorization.check(StoryRepository.fetch(params[:id])) @@ -52,6 +43,16 @@ def keep_unread render_replacements(Components::StoryKeepUnread.replacements(story)) end + # Marks the story read when it opens, unless it's kept unread. Responds + # with a Turbo Stream that replaces the keep unread form with the saved + # state, which the story controller copies onto the story. + def read + story = authorization.check(StoryRepository.fetch(params[:id])) + story.update!(is_read: true) unless story.keep_unread + + render_replacements(Components::StoryKeepUnread.replacements(story)) + end + def mark_all_as_read stories = authorization.scope(Story.where(id: params[:story_ids])) MarkAllAsRead.call(stories.ids) diff --git a/app/javascript/controllers/story_controller.ts b/app/javascript/controllers/story_controller.ts index 6fb4308f5..d7a0ceb3b 100644 --- a/app/javascript/controllers/story_controller.ts +++ b/app/javascript/controllers/story_controller.ts @@ -1,7 +1,5 @@ import { Controller } from "@hotwired/stimulus"; -import { updateStory } from "helpers/api"; - // Cmd, ctrl and middle clicks open the story in a background tab. function opensInTab(event: MouseEvent): boolean { return event.metaKey || event.ctrlKey || event.button === 1; @@ -9,23 +7,25 @@ function opensInTab(event: MouseEvent): boolean { /* * Owns a story's open and read state: the "open" and "read" classes on its - * element, saving read state to the server, and announcing changes as - * bubbling "story:opened" and "story:read-changed" events. + * element, and bubbling "story:opened" and "story:read-changed" events. + * Saving goes through forms in the story's Turbo Frame; the controller never + * talks to the server itself. */ export default class extends Controller { - static override values = { id: String, isRead: Boolean, keepUnread: Boolean }; + static override values = { isRead: Boolean, keepUnread: Boolean }; /* * The permalink sits inside the story's Turbo Frame, so a refresh updates - * it. The readState target is the keep unread form, which the server - * replaces with the saved read and keep unread state. + * it. The markRead form saves read state when the story opens. The + * readState target is the keep unread form, which the server replaces with + * the saved read and keep unread state. */ - static override targets = ["permalink", "readState"]; - - declare idValue: string; + static override targets = ["permalink", "markRead", "readState"]; declare permalinkTarget: HTMLAnchorElement; + declare markReadTarget: HTMLFormElement; + declare isReadValue: boolean; declare keepUnreadValue: boolean; @@ -72,22 +72,16 @@ export default class extends Controller { } } + /* + * Asks the server to mark the story read. The response replaces the + * readState target, which applies the "read" class once it's saved. + */ markAsRead(): void { if (this.isReadValue || this.keepUnreadValue) { return; } - this.isReadValue = true; - this.element.classList.add("read"); - this.dispatch("read-changed"); - - if (this.isSample()) { - return; - } - - updateStory(this.idValue, { is_read: true }).catch(() => { - // Optimistic UI — ignore server errors - }); + this.markReadTarget.requestSubmit(); } // Copies the saved state from a newly rendered keep unread form. @@ -116,11 +110,6 @@ export default class extends Controller { } } - // Sample stories on the tutorial page have fake, non-positive ids. - private isSample(): boolean { - return Number(this.idValue) <= 0; - } - private openInBackgroundTab(): void { window.open(this.permalinkTarget.href); window.focus(); diff --git a/app/javascript/controllers/tutorial_stories_controller.ts b/app/javascript/controllers/tutorial_stories_controller.ts index a8a56a23d..30694d0a8 100644 --- a/app/javascript/controllers/tutorial_stories_controller.ts +++ b/app/javascript/controllers/tutorial_stories_controller.ts @@ -28,22 +28,44 @@ function setIcon(form: HTMLFormElement, icon: string): void { } /* - * Swaps in an updated copy of the keep unread form, like the keep unread - * stream does. The story controller copies the new state onto the story + * Swaps in an updated copy of the keep unread form, like the keep unread and + * read streams do. The story controller copies the new state onto the story * when the copy connects. */ +function replaceReadState( + form: HTMLFormElement, + update: (copy: HTMLFormElement) => void, +): void { + const copy = form.cloneNode(true); + if (copy instanceof HTMLFormElement) { + update(copy); + form.replaceWith(copy); + } +} + function keepUnread(form: HTMLFormElement): void { const kept = hiddenValue(form, "keep_unread").value === "true"; - const copy = form.cloneNode(true); - if (!(copy instanceof HTMLFormElement)) { + + replaceReadState(form, (copy) => { + copy.dataset.keepUnread = String(kept); + copy.dataset.isRead = String(!kept); + hiddenValue(copy, "keep_unread").value = String(!kept); + setIcon(copy, keepUnreadIcon(kept)); + }); +} + +// Marks the story read through its keep unread form, like the read stream. +function markRead(form: HTMLFormElement): void { + const story = form.closest("li.story"); + const keepUnreadForm = + story?.querySelector(".story-keep-unread-form"); + if (!keepUnreadForm) { return; } - copy.dataset.keepUnread = String(kept); - copy.dataset.isRead = String(!kept); - hiddenValue(copy, "keep_unread").value = String(!kept); - setIcon(copy, keepUnreadIcon(kept)); - form.replaceWith(copy); + replaceReadState(keepUnreadForm, (copy) => { + copy.dataset.isRead = "true"; + }); } // Spins the refresh icon for a moment, as a real refresh does. @@ -79,6 +101,8 @@ export default class extends Controller { this.star(form); } else if (form.classList.contains("story-keep-unread-form")) { keepUnread(form); + } else if (form.classList.contains("story-mark-read-form")) { + markRead(form); } else if (form.classList.contains("story-refresh-form")) { refresh(form); } diff --git a/app/javascript/helpers/api.ts b/app/javascript/helpers/api.ts deleted file mode 100644 index 24751b743..000000000 --- a/app/javascript/helpers/api.ts +++ /dev/null @@ -1,22 +0,0 @@ -function csrfToken(): string { - const tag = - document.querySelector("meta[name='csrf-token']"); - - return tag?.content ?? ""; -} - -async function updateStory( - id: string, - attributes: {[key: string]: unknown}, -): Promise { - return fetch(`/stories/${id}`, { - body: JSON.stringify(attributes), - headers: { - "Content-Type": "application/json", - "X-CSRF-Token": csrfToken(), - }, - method: "PUT", - }); -} - -export {updateStory}; diff --git a/config/routes.rb b/config/routes.rb index 78ce09bde..926a5c8e7 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -36,9 +36,9 @@ get "/setup/password", to: "passwords#new" get "/setup/tutorial", to: "tutorials#index" get "/starred", to: "stories#starred" - put "/stories/:id", to: "stories#update" post "/stories/:id/refresh", to: "stories#refresh" patch "/stories/:id/star", to: "stories#star" patch "/stories/:id/keep_unread", to: "stories#keep_unread" + patch "/stories/:id/read", to: "stories#read" post "/stories/mark_all_as_read", to: "stories#mark_all_as_read" end diff --git a/spec/components/story_spec.rb b/spec/components/story_spec.rb index 962483057..6e49f683d 100644 --- a/spec/components/story_spec.rb +++ b/spec/components/story_spec.rb @@ -18,14 +18,31 @@ def story_li(story) end def values(element) - names = ["story-id", "story-is-read", "story-keep-unread"] + names = ["story-is-read", "story-keep-unread"] names.map { |name| element["data-#{name}-value"] } end it "sets the Stimulus values on the li" do story = create(:story, keep_unread: true) - expect(values(story_li(story))).to eq([story.id.to_s, "false", "true"]) + expect(values(story_li(story))).to eq(["false", "true"]) + end + + it "includes a hidden form for marking the story read" do + story = create(:story) + form = render_story(story).find("form.story-mark-read-form", visible: :all) + + expect([form[:action], form["data-story-target"]]) + .to eq(["/stories/#{story.id}/read", "markRead"]) + end + + it "doesn't nest the story's other forms inside the mark read form" do + rendered = render_story(create(:story)) + + expect(rendered).to have_no_css( + "form.story-mark-read-form form", + visible: :all + ) end it "keeps the story in place when a refresh fails" do @@ -141,7 +158,7 @@ def values(element) it "posts the refresh form to the story's refresh path" do story = create(:story) - form = render_story(story).find("form:has(button.story-refresh)") + form = render_story(story).find("form.story-refresh-form") expect(form[:action]).to eq("/stories/#{story.id}/refresh") end diff --git a/spec/javascript/controllers/story_controller_open_spec.ts b/spec/javascript/controllers/story_controller_open_spec.ts index fcb268c3a..626a0fe60 100644 --- a/spec/javascript/controllers/story_controller_open_spec.ts +++ b/spec/javascript/controllers/story_controller_open_spec.ts @@ -3,26 +3,23 @@ import { controller, element, isOpen, - mockFetch, preview, setupController, + submittedMarkRead, } from "support/story_fixture"; import { ensure } from "helpers/ensure"; describe("open", () => { - it("adds the open class and marks the story read", async () => { + it("adds the open class and asks to mark the story read", async () => { await setupController(); - mockFetch(); controller().open(); - expect(isOpen()).toBe(true); - expect(element().classList.contains("read")).toBe(true); + expect([isOpen(), submittedMarkRead()]).toStrictEqual([true, true]); }); it("announces that it opened", async () => { await setupController(); - mockFetch(); const listener = vi.fn<(event: Event) => void>(); element().addEventListener("story:opened", listener); @@ -33,7 +30,6 @@ describe("open", () => { it("scrolls the story into view", async () => { await setupController(); - mockFetch(); const scrollSpy = vi.spyOn(element(), "scrollIntoView"); controller().open(); @@ -48,7 +44,6 @@ describe("open", () => { describe("close and toggle", () => { it("toggles the story open and closed", async () => { await setupController(); - mockFetch(); controller().toggle(); expect(isOpen()).toBe(true); @@ -59,7 +54,6 @@ describe("close and toggle", () => { it("does not scroll when closing", async () => { await setupController(); - mockFetch(); controller().open(); const scrollSpy = vi.spyOn(element(), "scrollIntoView"); @@ -72,7 +66,6 @@ describe("close and toggle", () => { describe("previewClicked", () => { it("opens and closes the story", async () => { await setupController(); - mockFetch(); clickPreview(); expect(isOpen()).toBe(true); @@ -83,7 +76,6 @@ describe("previewClicked", () => { it("scrolls the story into view when closed by a click", async () => { await setupController(); - mockFetch(); controller().open(); const scrollSpy = vi.spyOn(element(), "scrollIntoView"); @@ -98,7 +90,6 @@ describe("previewClicked", () => { describe("previewClicked on the star button", () => { it("leaves the story closed", async () => { await setupController(); - mockFetch(); const button = ensure(element().querySelector("#star button")); button.dispatchEvent(new MouseEvent("click", { bubbles: true })); @@ -114,7 +105,6 @@ describe("previewClicked with a modifier", () => { ["middle", { button: 1 }], ])("opens a tab on %s clicks and marks read", async (_name, options) => { await setupController(); - mockFetch(); const openSpy = vi.spyOn(window, "open").mockReturnValue(null); const focusSpy = vi.spyOn(window, "focus").mockReturnValue(); @@ -123,7 +113,7 @@ describe("previewClicked with a modifier", () => { expect(openSpy).toHaveBeenCalledExactlyOnceWith("http://example.com/story"); expect(focusSpy).toHaveBeenCalledExactlyOnceWith(); expect(isOpen()).toBe(false); - expect(element().classList.contains("read")).toBe(true); + expect(submittedMarkRead()).toBe(true); }); }); diff --git a/spec/javascript/controllers/story_controller_spec.ts b/spec/javascript/controllers/story_controller_spec.ts index ba4ef3e94..c9b4cbc10 100644 --- a/spec/javascript/controllers/story_controller_spec.ts +++ b/spec/javascript/controllers/story_controller_spec.ts @@ -2,87 +2,44 @@ import { controller, element, listenForReadChanged, - mockFetch, replaceReadState, setupController, + submittedMarkRead, } from "support/story_fixture"; describe("markAsRead", () => { - it("adds the read class", async () => { + it("asks the server to mark the story read", async () => { await setupController(); - mockFetch(); controller().markAsRead(); - expect(element().classList.contains("read")).toBe(true); + expect(submittedMarkRead()).toBe(true); }); - it("announces the change", async () => { + it("waits for the server before adding the read class", async () => { await setupController(); - mockFetch(); const listener = listenForReadChanged(); controller().markAsRead(); - expect(listener).toHaveBeenCalledExactlyOnceWith(expect.any(CustomEvent)); + expect([element().classList.contains("read"), listener.mock.calls]) + .toStrictEqual([false, []]); }); - it("saves is_read to the server", async () => { - await setupController(); - const fetchSpy = mockFetch(); - - controller().markAsRead(); - - expect(fetchSpy).toHaveBeenCalledWith( - "/stories/42", - expect.objectContaining({ - body: JSON.stringify({ is_read: true }), - method: "PUT", - }), - ); - }); -}); - -describe("markAsRead when it should not save", () => { it("does nothing when the story is already read", async () => { await setupController({ isRead: true }); - const fetchSpy = mockFetch(); - const listener = listenForReadChanged(); controller().markAsRead(); - expect(fetchSpy).not.toHaveBeenCalled(); - expect(listener).not.toHaveBeenCalled(); + expect(submittedMarkRead()).toBe(false); }); it("does nothing when the story is kept unread", async () => { await setupController({ keepUnread: true }); - const fetchSpy = mockFetch(); - - controller().markAsRead(); - - expect(fetchSpy).not.toHaveBeenCalled(); - expect(element().classList.contains("read")).toBe(false); - }); - - it("does not save sample stories with fake ids", async () => { - await setupController({ id: "-5" }); - const fetchSpy = mockFetch(); - - controller().markAsRead(); - - expect(fetchSpy).not.toHaveBeenCalled(); - expect(element().classList.contains("read")).toBe(true); - }); - - it("ignores server errors", async () => { - await setupController(); - vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("offline")); controller().markAsRead(); - await Promise.resolve(); - expect(element().classList.contains("read")).toBe(true); + expect(submittedMarkRead()).toBe(false); }); }); @@ -115,21 +72,19 @@ describe("readStateTargetConnected", () => { it("stops markAsRead while kept unread", async () => { await setupController({ isRead: true }); - const fetchSpy = mockFetch(); await replaceReadState({ isRead: false, keepUnread: true }); controller().markAsRead(); - expect(fetchSpy).not.toHaveBeenCalled(); + expect(submittedMarkRead()).toBe(false); }); it("lets markAsRead work again once no longer kept unread", async () => { await setupController({ keepUnread: true }); - mockFetch(); await replaceReadState({ isRead: false, keepUnread: false }); controller().markAsRead(); - expect(element().classList.contains("read")).toBe(true); + expect(submittedMarkRead()).toBe(true); }); }); diff --git a/spec/javascript/controllers/story_list_controller_spec.ts b/spec/javascript/controllers/story_list_controller_spec.ts index c6238f2cb..6d158d6be 100644 --- a/spec/javascript/controllers/story_list_controller_spec.ts +++ b/spec/javascript/controllers/story_list_controller_spec.ts @@ -2,15 +2,15 @@ import { bootStimulus, getController } from "support/stimulus"; import StoryController from "controllers/story_controller"; import StoryListController from "controllers/story_list_controller"; import { ensure } from "helpers/ensure"; +import { stubFormSubmits } from "support/story_fixture"; -// Sample ids skip saving read state, so these specs make no requests. function storyHTML(title: string): string { return [ "
  • ", ` ${title}`, + "
    ", "
  • ", ].join("\n"); } @@ -33,6 +33,8 @@ function setupDOM(): void { async function setupController(): Promise { setupDOM(); + // Opening a story submits its mark read form, which jsdom can't do. + stubFormSubmits(); await bootStimulus("story", StoryController); await bootStimulus("story-list", StoryListController); } diff --git a/spec/javascript/controllers/tutorial_stories_controller_spec.ts b/spec/javascript/controllers/tutorial_stories_controller_spec.ts index a3e2f4596..a82f11ec8 100644 --- a/spec/javascript/controllers/tutorial_stories_controller_spec.ts +++ b/spec/javascript/controllers/tutorial_stories_controller_spec.ts @@ -28,6 +28,7 @@ async function setupController(): Promise { " ", " ", "
    ", + "
    ", " ", "", ].join("\n"); @@ -113,6 +114,19 @@ describe("submitted for the keep unread form", () => { }); }); +describe("submitted for the mark read form", () => { + it("swaps in a keep unread form that says the story is read", async () => { + await setupController(); + form(".story-keep-unread-form").dataset.isRead = "false"; + + submit(".story-mark-read-form"); + + const copy = form(".story-keep-unread-form"); + expect([copy.dataset.isRead, copy.dataset.keepUnread]) + .toStrictEqual(["true", "false"]); + }); +}); + describe("submitted for the refresh form", () => { it("marks the form busy for a moment", async () => { vi.useFakeTimers(); diff --git a/spec/javascript/helpers/api_spec.ts b/spec/javascript/helpers/api_spec.ts deleted file mode 100644 index 53b9e4098..000000000 --- a/spec/javascript/helpers/api_spec.ts +++ /dev/null @@ -1,42 +0,0 @@ -import {updateStory} from "helpers/api"; - -describe("updateStory", () => { - afterEach(() => { - vi.restoreAllMocks(); - }); - - it("sends a PUT with JSON body and CSRF token", async () => { - const mockResponse = new Response("", {status: 200}); - const fetchSpy = vi.spyOn(globalThis, "fetch"). - mockResolvedValue(mockResponse); - - const meta = document.createElement("meta"); - meta.name = "csrf-token"; - meta.content = "test-token"; - document.head.appendChild(meta); - await updateStory("42", {is_starred: true}); - - expect(fetchSpy).toHaveBeenCalledWith("/stories/42", { - body: JSON.stringify({is_starred: true}), - headers: { - "Content-Type": "application/json", - "X-CSRF-Token": "test-token", - }, - method: "PUT", - }); - - meta.remove(); - }); - - it("sends empty CSRF token when meta tag is missing", async () => { - const fetchSpy = vi.spyOn(globalThis, "fetch"). - mockResolvedValue(new Response()); - await updateStory("1", {is_starred: false}); - - expect(fetchSpy).toHaveBeenCalledTimes(1); - - const {headers} = fetchSpy.mock.calls[0]?.[1] ?? {}; - - expect(headers).toHaveProperty("X-CSRF-Token", ""); - }); -}); diff --git a/spec/javascript/support/story_fixture.ts b/spec/javascript/support/story_fixture.ts index 713894586..76da60010 100644 --- a/spec/javascript/support/story_fixture.ts +++ b/spec/javascript/support/story_fixture.ts @@ -5,7 +5,7 @@ import { ensure } from "helpers/ensure"; // Shared fixture for the story controller specs. -interface Options { id?: string; isRead?: boolean; keepUnread?: boolean } +interface Options { isRead?: boolean; keepUnread?: boolean } interface ReadState { isRead: boolean; keepUnread: boolean } @@ -19,20 +19,19 @@ function readStateHTML({ isRead, keepUnread }: ReadState): string { ].join("\n"); } -function setupDOM({ id = "42", isRead = false, keepUnread = false }: Options): -void { +function setupDOM({ isRead = false, keepUnread = false }: Options): void { // Static test fixture — safe to use innerHTML document.body.innerHTML = [ "
  • `, "
    ", "
    ", "
    ", + "
    ", " ", "
    ", readStateHTML({ isRead, keepUnread }), @@ -40,8 +39,22 @@ void { ].join("\n"); } +let formSubmits: MockInstance | null = null; + +/* + * Jsdom can't submit forms, so specs stub requestSubmit. Its mock contexts + * show which forms were submitted; replaceReadState fakes the response. + */ +function stubFormSubmits(): MockInstance { + formSubmits = vi.spyOn(HTMLFormElement.prototype, "requestSubmit") + .mockReturnValue(); + + return formSubmits; +} + async function setupController(options: Options = {}): Promise { setupDOM(options); + stubFormSubmits(); await bootStimulus("story", StoryController); } @@ -53,9 +66,15 @@ function controller(): StoryController { return getController(element(), "story", StoryController); } -function mockFetch(): MockInstance { - return vi.spyOn(globalThis, "fetch") - .mockResolvedValue(new Response(null, { status: 204 })); +function markReadForm(): HTMLFormElement { + const selector = ".story-mark-read-form"; + + return ensure(element().querySelector(selector)); +} + +// Whether the story asked the server to mark it read. +function submittedMarkRead(): boolean { + return ensure(formSubmits).mock.contexts.includes(markReadForm()); } function listenForReadChanged(): MockInstance { @@ -91,8 +110,9 @@ export { element, isOpen, listenForReadChanged, - mockFetch, preview, replaceReadState, setupController, + stubFormSubmits, + submittedMarkRead, }; diff --git a/spec/requests/stories_controller_spec.rb b/spec/requests/stories_controller_spec.rb index cf548461e..2257aa3ca 100644 --- a/spec/requests/stories_controller_spec.rb +++ b/spec/requests/stories_controller_spec.rb @@ -109,64 +109,6 @@ end end - describe "#update" do - headers = { "CONTENT_TYPE" => "application/json" } - - it "marks a story as read when it is_read not malformed" do - login_as(default_user) - story = create(:story) - params = { is_read: true }.to_json - - expect { put("/stories/#{story.id}", params:, headers:) } - .to change_record(story, :is_read).from(false).to(true) - end - - it "marks a story as read when is_read is malformed" do - login_as(default_user) - story = create(:story) - params = { is_read: "malformed" }.to_json - - expect { put("/stories/#{story.id}", params:, headers:) } - .to change_record(story, :is_read).from(false).to(true) - end - - it "marks a story as keep unread when it keep_unread not malformed" do - login_as(default_user) - story = create(:story) - params = { keep_unread: true }.to_json - - expect { put("/stories/#{story.id}", params:, headers:) } - .to change_record(story, :keep_unread).from(false).to(true) - end - - it "marks a story as keep unread when keep_unread is malformed" do - login_as(default_user) - story = create(:story) - params = { keep_unread: "malformed" }.to_json - - expect { put("/stories/#{story.id}", params:, headers:) } - .to change_record(story, :keep_unread).from(false).to(true) - end - - it "marks a story as starred when is_starred is not malformed" do - login_as(default_user) - story = create(:story) - params = { is_starred: true }.to_json - - expect { put("/stories/#{story.id}", params:, headers:) } - .to change_record(story, :is_starred).from(false).to(true) - end - - it "marks a story as starred when is_starred is malformed" do - login_as(default_user) - story = create(:story) - params = { is_starred: "malformed" }.to_json - - expect { put("/stories/#{story.id}", params:, headers:) } - .to change_record(story, :is_starred).from(false).to(true) - end - end - describe "#refresh" do def updated_entry double( @@ -313,6 +255,36 @@ def keep_unread(story, value) end end + describe "#read" do + def read(story) + patch("/stories/#{story.id}/read") + end + + it "marks the story read" do + login_as(default_user) + story = create(:story) + + expect { read(story) }.to change_record(story, :is_read).to(true) + end + + it "leaves a story kept unread alone" do + login_as(default_user) + story = create(:story, keep_unread: true) + + expect { read(story) }.not_to change_record(story, :is_read) + end + + it "replaces the keep unread form with the saved state" do + login_as(default_user) + story = create(:story) + + read(story) + + expect(rendered.find("turbo-stream", visible: :all)[:target]) + .to eq("story_#{story.id}_keep_unread") + end + end + describe "#mark_all_as_read" do it "marks all unread stories as read and reload the page" do login_as(default_user)