Compare commits

..

1 Commits

Author SHA1 Message Date
google-labs-jules[bot]
f2421bf4c7 Here's the plan to add polymorphic comments and update related functionality:
This change introduces polymorphic comments, allowing you to comment on Photos, Plantings, Harvests, and Activities, in addition to Posts.

Key changes include:

-   **Comment Model:**
    -   Made `Comment.commentable` a polymorphic association.
    -   Added a data migration to move existing post comments to the new structure.
    -   Updated notification creation logic for polymorphic commentables.
-   **CommentsController:**
    -   Refactored to handle various commentable types using a `find_commentable` method.
-   **Ability Model:**
    -   Updated permissions for comment creation, editing (author/admin), and deletion (author/commentable owner/admin).
-   **Routes:**
    -   Added nested comment routes for Photos, Plantings, Harvests, Activities, and Posts using a `commentable` concern with shallow routes.
-   **Views:**
    -   Created generic partials for comment forms (`_form.html.haml`) and display (`_comment.html.haml`, `_comments.html.haml`).
    -   Integrated these partials into the show pages of all commentable types.
    -   Updated `comments/new` and `comments/edit` views to be generic.
    -   Relevant parent controller `show` actions now eager-load comments.
-   **Testing:**
    -   Added extensive model, controller (using shared examples), and feature tests to cover the new polymorphic comment functionality, including permissions and UI interactions for all commentable types.
    -   Updated and created factories as needed.

This fulfills the issue requirements for adding comments to multiple resource types with appropriate permissions.
2025-05-25 02:03:17 +00:00
77 changed files with 1659 additions and 1066 deletions

47
.codeclimate.yml Normal file
View File

@@ -0,0 +1,47 @@
plugins:
brakeman:
enabled: false # codeclimate's brakeman is stuck in rails 5 rules
bundler-audit:
enabled: true
coffeelint:
enabled: true
duplication:
enabled: true
config:
languages:
- ruby
- javascript
editorconfig:
enabled: true
eslint:
enabled: true
fixme:
enabled: true
haml-lint:
enabled: true
nodesecurity:
enabled: true
rubocop:
enabled: true
channel: "rubocop-1-11"
scss-lint:
enabled: true
shellcheck:
enabled: true
ratings:
paths:
- "**.rb"
- "**.ru"
- "**.js"
- "**.coffee"
- "**.scss"
- "**.haml"
- Gemfile.lock
exclude_paths:
- config/
- db/
- spec/
- public/
- app/assets/stylesheets/bootstrap-accessibility.css
- app/assets/javascripts/bootstrap*
- app/assets/stylesheets/leaflet_overrides.scss

View File

@@ -1,102 +0,0 @@
name: CI Features - Admin
on: [pull_request]
jobs:
rspec:
runs-on: ubuntu-latest
services:
db:
image: postgres
env:
##
# The Postgres service fails its docker health check unless you
# specify these environment variables
#
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: growstuff_test
ports: ['5432:5432']
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
env:
APP_DOMAIN_NAME: localhost:3000
APP_PROTOCOL: http
CC_TEST_REPORTER_ID: ${{ secrets.CC_TEST_REPORTER_ID }}
DATABASE_URL: postgres://postgres:postgres@localhost:5432/growstuff_test
DEVISE_SECRET_KEY: secret
ELASTIC_SEARCH_VERSION: "7.5.1-amd64"
GROWSTUFF_EMAIL: "noreply@test.growstuff.org"
GROWSTUFF_FLICKR_KEY: secretkey"
GROWSTUFF_FLICKR_SECRET: secretsecret
GROWSTUFF_SITE_NAME: "Growstuff (travis)"
RAILS_ENV: test
RAILS_SECRET_TOKEN: supersecret
steps:
- name: Checkout this repo
uses: actions/checkout@v4
- name: Configure sysctl limits
run: |
sudo swapoff -a
sudo sysctl -w vm.swappiness=1
sudo sysctl -w fs.file-max=262144
sudo sysctl -w vm.max_map_count=262144
- name: Start Elasticsearch
uses: elastic/elastic-github-actions/elasticsearch@master
with:
stack-version: 7.5.1
##
# Cache Yarn modules
#
# See https://github.com/actions/cache/blob/master/examples.md#node---yarn for details
#
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- name: Setup yarn cache
uses: actions/cache@v4
id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: Install required OS packages
run: |
sudo apt-get -y install libpq-dev google-chrome-stable
- name: Install NodeJS
uses: actions/setup-node@v4
with:
node-version: '12'
- name: Install Ruby (version given by .ruby-version) and Bundler
uses: ruby/setup-ruby@v1
with:
bundler-cache: true
- name: Install required JS packages
run: yarn install
- name: install chrome
run: sudo apt-get install google-chrome-stable
- name: Prepare database for testing
run: bundle exec rails db:prepare
- name: precompile assets
run: bundle exec rails assets:precompile
- name: index into elastic search
run: bundle exec rails search:reindex
- name: Run rspec (places/)
run: bundle exec rspec spec/features/places/ -fd

View File

@@ -1,102 +0,0 @@
name: CI Features - Admin
on: [pull_request]
jobs:
rspec:
runs-on: ubuntu-latest
services:
db:
image: postgres
env:
##
# The Postgres service fails its docker health check unless you
# specify these environment variables
#
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: growstuff_test
ports: ['5432:5432']
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
env:
APP_DOMAIN_NAME: localhost:3000
APP_PROTOCOL: http
CC_TEST_REPORTER_ID: ${{ secrets.CC_TEST_REPORTER_ID }}
DATABASE_URL: postgres://postgres:postgres@localhost:5432/growstuff_test
DEVISE_SECRET_KEY: secret
ELASTIC_SEARCH_VERSION: "7.5.1-amd64"
GROWSTUFF_EMAIL: "noreply@test.growstuff.org"
GROWSTUFF_FLICKR_KEY: secretkey"
GROWSTUFF_FLICKR_SECRET: secretsecret
GROWSTUFF_SITE_NAME: "Growstuff (travis)"
RAILS_ENV: test
RAILS_SECRET_TOKEN: supersecret
steps:
- name: Checkout this repo
uses: actions/checkout@v4
- name: Configure sysctl limits
run: |
sudo swapoff -a
sudo sysctl -w vm.swappiness=1
sudo sysctl -w fs.file-max=262144
sudo sysctl -w vm.max_map_count=262144
- name: Start Elasticsearch
uses: elastic/elastic-github-actions/elasticsearch@master
with:
stack-version: 7.5.1
##
# Cache Yarn modules
#
# See https://github.com/actions/cache/blob/master/examples.md#node---yarn for details
#
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- name: Setup yarn cache
uses: actions/cache@v4
id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: Install required OS packages
run: |
sudo apt-get -y install libpq-dev google-chrome-stable
- name: Install NodeJS
uses: actions/setup-node@v4
with:
node-version: '12'
- name: Install Ruby (version given by .ruby-version) and Bundler
uses: ruby/setup-ruby@v1
with:
bundler-cache: true
- name: Install required JS packages
run: yarn install
- name: install chrome
run: sudo apt-get install google-chrome-stable
- name: Prepare database for testing
run: bundle exec rails db:prepare
- name: precompile assets
run: bundle exec rails assets:precompile
- name: index into elastic search
run: bundle exec rails search:reindex
- name: Run rspec (posts/)
run: bundle exec rspec spec/features/posts/ -fd

View File

@@ -107,5 +107,19 @@ jobs:
- name: Run rspec (photos/)
run: bundle exec rspec spec/features/photos/ -fd
- name: Run rspec (places/)
run: bundle exec rspec spec/features/places/ -fd
- name: Run rspec (plantings/)
run: bundle exec rspec spec/features/plantings/ -fd
- name: Run rspec (posts/)
run: bundle exec rspec spec/features/posts/ -fd
- name: Run rspec (rss/)
run: bundle exec rspec spec/features/rss/ -fd
run: bundle exec rspec spec/features/rss/ -fd
- name: Report to code climate
run: |
gem install codeclimate-test-reporter
codeclimate-test-reporter

View File

@@ -127,4 +127,9 @@ jobs:
run: bundle exec rspec spec/routing/ -fd --fail-fast
- name: Run rspec (request)
run: bundle exec rspec spec/requests/ -fd --fail-fast
run: bundle exec rspec spec/requests/ -fd --fail-fast
- name: Report to code climate
run: |
gem install codeclimate-test-reporter
codeclimate-test-reporter

View File

@@ -1 +1 @@
3.3.8
3.3.7

View File

@@ -175,7 +175,6 @@ group :development, :test do
gem 'rubocop-rspec_rails'
gem 'webrat' # provides HTML matchers for view tests
gem 'crowdin-cli' # for translations
gem 'dotenv-rails'
# cli utils
@@ -189,16 +188,15 @@ end
group :test do
gem 'axe-core-capybara'
gem 'axe-core-rspec'
gem 'codeclimate-test-reporter', require: false
gem 'rails-controller-testing'
gem 'selenium-webdriver'
gem 'timecop'
gem 'vcr'
gem "rspec-rebound"
gem "percy-capybara", "~> 5.0.0"
end
group :travis do
gem 'platform-api'
end
gem "percy-capybara", "~> 5.0.0"

View File

@@ -135,14 +135,14 @@ GEM
descendants_tracker (~> 0.0.4)
ice_nine (~> 0.11.0)
thread_safe (~> 0.3, >= 0.3.1)
base64 (0.3.0)
base64 (0.2.0)
bcrypt (3.1.20)
benchmark (0.4.1)
benchmark (0.4.0)
better_errors (2.10.1)
erubi (>= 1.0.0)
rack (>= 0.9.0)
rouge (>= 1.0.0)
bigdecimal (3.2.2)
bigdecimal (3.1.9)
bluecloth (2.2.0)
bonsai-elasticsearch-rails (7.0.1)
elasticsearch-model (< 8)
@@ -156,7 +156,7 @@ GEM
actionpack (>= 6.1)
activemodel (>= 6.1)
builder (3.3.0)
bullet (8.0.8)
bullet (8.0.7)
activesupport (>= 3.0.0)
uniform_notifier (~> 1.11)
byebug (12.0.0)
@@ -185,6 +185,8 @@ GEM
ssrf_filter (~> 1.0)
chartkick (5.1.5)
childprocess (5.0.0)
codeclimate-test-reporter (1.0.9)
simplecov (<= 0.13)
coderay (1.1.3)
coercible (1.0.0)
descendants_tracker (~> 0.0.1)
@@ -200,14 +202,6 @@ GEM
concurrent-ruby (1.3.5)
connection_pool (2.5.3)
crass (1.0.6)
crowdin-api (1.12.0)
open-uri (>= 0.1.0, < 0.2.0)
rest-client (>= 2.0.0, < 2.2.0)
crowdin-cli (0.2.2)
crowdin-api (>= 0.2.0)
gli (>= 2.7.0)
i18n (>= 0.6.4)
rubyzip (>= 1.0.0)
csv (3.3.1)
csv_shaper (1.4.0)
activesupport (>= 3.0.0)
@@ -228,15 +222,15 @@ GEM
railties (>= 4.1.0)
responders
warden (~> 1.2.3)
diff-lcs (1.6.2)
diff-lcs (1.6.1)
discard (1.4.0)
activerecord (>= 4.2, < 9.0)
domain_name (0.6.20240107)
docile (1.1.5)
dotenv (3.1.8)
dotenv-rails (3.1.8)
dotenv (= 3.1.8)
railties (>= 6.1)
drb (2.2.3)
drb (2.2.1)
dumb_delegator (1.1.0)
elasticsearch (7.0.0)
elasticsearch-api (= 7.0.0)
@@ -251,24 +245,23 @@ GEM
elasticsearch-transport (7.0.0)
faraday
multi_json
erb (5.0.1)
erubi (1.13.1)
erubis (2.7.0)
excon (1.2.5)
logger
execjs (2.10.0)
factory_bot (6.5.4)
activesupport (>= 6.1.0)
factory_bot_rails (6.5.0)
factory_bot (6.5.0)
activesupport (>= 5.0.0)
factory_bot_rails (6.4.4)
factory_bot (~> 6.5)
railties (>= 6.1.0)
faker (3.5.2)
railties (>= 5.0.0)
faker (3.5.1)
i18n (>= 1.8.11, < 2)
faraday (2.13.4)
faraday (2.13.1)
faraday-net_http (>= 2.0, < 3.5)
json
logger
faraday-net_http (3.4.1)
faraday-net_http (3.4.0)
net-http (>= 0.5.0)
ffi (1.16.3)
flickraw (0.9.10)
@@ -283,8 +276,6 @@ GEM
gibbon (1.2.1)
httparty
multi_json (>= 1.9.0)
gli (2.22.2)
ostruct
globalid (1.2.1)
activesupport (>= 6.1)
gravatar-ultimate (2.0.0)
@@ -305,7 +296,7 @@ GEM
activesupport (>= 5.1)
haml (>= 4.0.6)
railties (>= 5.1)
haml_lint (0.66.0)
haml_lint (0.62.0)
haml (>= 5.0)
parallel (~> 1.10)
rainbow
@@ -321,9 +312,6 @@ GEM
webrick
highline (3.1.2)
reline
http-accept (1.7.0)
http-cookie (1.0.8)
domain_name (~> 0.5)
httparty (0.22.0)
csv
mini_mime (>= 1.0.0)
@@ -341,7 +329,7 @@ GEM
rainbow (>= 2.2.2, < 4.0)
ruby-progressbar (~> 1.8, >= 1.8.1)
terminal-table (>= 1.5.1)
icalendar (2.11.2)
icalendar (2.11.0)
base64
ice_cube (~> 0.16)
logger
@@ -360,7 +348,7 @@ GEM
rails-dom-testing (>= 1, < 3)
railties (>= 4.2.0)
thor (>= 0.14, < 2.0)
json (2.13.2)
json (2.12.0)
json-schema (5.1.0)
addressable (~> 2.8)
jsonapi-resources (0.10.7)
@@ -405,10 +393,6 @@ GEM
matrix (0.4.2)
memcachier (0.0.2)
method_source (1.1.0)
mime-types (3.7.0)
logger
mime-types-data (~> 3.2025, >= 3.2025.0507)
mime-types-data (3.2025.0805)
mimemagic (0.4.3)
nokogiri (~> 1)
rake
@@ -432,12 +416,11 @@ GEM
timeout
net-smtp (0.5.0)
net-protocol
netrc (0.11.0)
nio4r (2.7.4)
nokogiri (1.18.9)
nokogiri (1.18.8)
mini_portile2 (~> 2.8.2)
racc (~> 1.4)
nokogiri (1.18.9-x86_64-linux-gnu)
nokogiri (1.18.8-x86_64-linux-gnu)
racc (~> 1.4)
oauth (0.5.6)
oj (3.16.10)
@@ -455,17 +438,15 @@ GEM
omniauth-twitter (1.4.0)
omniauth-oauth (~> 1.1)
rack
open-uri (0.1.0)
orm_adapter (0.5.0)
ostruct (0.6.2)
ostruct (0.6.1)
parallel (1.27.0)
parser (3.3.9.0)
parser (3.3.8.0)
ast (~> 2.4.1)
racc
percy-capybara (5.0.0)
capybara (>= 3)
pg (1.6.1)
pg (1.6.1-x86_64-linux)
pg (1.5.9)
platform-api (3.8.0)
heroics (~> 0.1.1)
moneta (~> 1.0.0)
@@ -482,11 +463,11 @@ GEM
date
stringio
public_suffix (6.0.1)
puma (6.6.1)
puma (6.6.0)
nio4r (~> 2.0)
query_diet (0.7.2)
racc (1.8.1)
rack (2.2.17)
rack (2.2.15)
rack-cors (2.0.2)
rack (>= 2.0.0)
rack-protection (3.2.0)
@@ -517,7 +498,7 @@ GEM
actionpack (>= 5.0.1.rc1)
actionview (>= 5.0.1.rc1)
activesupport (>= 5.0.1.rc1)
rails-dom-testing (2.3.0)
rails-dom-testing (2.2.0)
activesupport (>= 5.0.0)
minitest
nokogiri (>= 1.6)
@@ -542,47 +523,41 @@ GEM
zeitwerk (~> 2.6)
rainbow (3.1.1)
raindrops (0.20.1)
rake (13.3.0)
rake (13.2.1)
rate_throttle_client (0.1.2)
rb-fsevent (0.11.2)
rb-inotify (0.10.1)
ffi (~> 1.0)
rdoc (6.14.2)
erb
rdoc (6.13.1)
psych (>= 4.0.0)
recaptcha (5.20.1)
recaptcha (5.19.0)
redis-client (0.23.2)
connection_pool
regexp_parser (2.11.1)
regexp_parser (2.10.0)
reline (0.6.1)
io-console (~> 0.5)
responders (3.1.1)
actionpack (>= 5.2)
railties (>= 5.2)
rest-client (2.1.0)
http-accept (>= 1.7.0, < 2.0)
http-cookie (>= 1.0.2, < 2.0)
mime-types (>= 1.16, < 4.0)
netrc (~> 0.8)
rexml (3.4.1)
rouge (4.1.2)
rspec (3.13.0)
rspec-core (~> 3.13.0)
rspec-expectations (~> 3.13.0)
rspec-mocks (~> 3.13.0)
rspec-activemodel-mocks (1.3.0)
rspec-activemodel-mocks (1.2.1)
activemodel (>= 3.0)
activesupport (>= 3.0)
rspec-mocks (>= 2.99, < 4.0)
rspec-core (3.13.5)
rspec-core (3.13.3)
rspec-support (~> 3.13.0)
rspec-expectations (3.13.5)
rspec-expectations (3.13.4)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.13.0)
rspec-mocks (3.13.5)
rspec-mocks (3.13.4)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.13.0)
rspec-rails (8.0.1)
rspec-rails (8.0.0)
actionpack (>= 7.2)
activesupport (>= 7.2)
railties (>= 7.2)
@@ -590,9 +565,7 @@ GEM
rspec-expectations (~> 3.13)
rspec-mocks (~> 3.13)
rspec-support (~> 3.13)
rspec-rebound (0.2.1)
rspec-core (~> 3.3)
rspec-support (3.13.4)
rspec-support (3.13.3)
rspectre (0.2.0)
parser (>= 3.3.7.1)
prism (~> 1.3)
@@ -608,7 +581,7 @@ GEM
rswag-ui (2.16.0)
actionpack (>= 5.2, < 8.1)
railties (>= 5.2, < 8.1)
rubocop (1.79.2)
rubocop (1.75.5)
json (~> 2.3)
language_server-protocol (~> 3.17.0.2)
lint_roller (~> 1.1.0)
@@ -616,10 +589,10 @@ GEM
parser (>= 3.3.0.2)
rainbow (>= 2.2.2, < 4.0)
regexp_parser (>= 2.9.3, < 3.0)
rubocop-ast (>= 1.46.0, < 2.0)
rubocop-ast (>= 1.44.0, < 2.0)
ruby-progressbar (~> 1.7)
unicode-display_width (>= 2.4.0, < 4.0)
rubocop-ast (1.46.0)
rubocop-ast (1.44.1)
parser (>= 3.3.7.2)
prism (~> 1.4)
rubocop-capybara (2.22.1)
@@ -662,13 +635,13 @@ GEM
sprockets (> 3.0)
sprockets-rails
tilt
scout_apm (5.7.0)
scout_apm (5.6.4)
parser
searchkick (5.3.1)
activemodel (>= 6.1)
hashie
securerandom (0.4.1)
selenium-webdriver (4.34.0)
selenium-webdriver (4.32.0)
base64 (~> 0.2)
logger (~> 1.4)
rexml (~> 3.2, >= 3.2.5)
@@ -680,6 +653,11 @@ GEM
logger
rack (>= 2.2.4)
redis-client (>= 0.22.2)
simplecov (0.13.0)
docile (~> 1.1.0)
json (>= 1.8, < 3)
simplecov-html (~> 0.10.0)
simplecov-html (0.10.2)
sprockets (3.7.5)
base64
concurrent-ruby (~> 1.0)
@@ -691,14 +669,14 @@ GEM
ssrf_filter (1.1.2)
stringio (3.1.7)
sysexits (1.2.0)
temple (0.10.4)
temple (0.10.3)
terminal-table (4.0.0)
unicode-display_width (>= 1.1.1, < 4)
terser (1.2.5)
execjs (>= 0.3.0, < 3)
thor (1.4.0)
thor (1.3.2)
thread_safe (0.3.6)
tilt (2.6.1)
tilt (2.6.0)
timecop (0.9.10)
timeout (0.4.3)
trollop (1.16.2)
@@ -740,7 +718,7 @@ GEM
webrick
xpath (3.2.0)
nokogiri (~> 1.8)
zeitwerk (2.7.3)
zeitwerk (2.7.2)
PLATFORMS
ruby
@@ -766,9 +744,9 @@ DEPENDENCIES
capybara-email
capybara-screenshot
chartkick
codeclimate-test-reporter
coffee-rails
comfortable_mexican_sofa!
crowdin-cli
csv_shaper
dalli
database_cleaner
@@ -827,7 +805,6 @@ DEPENDENCIES
responders
rspec-activemodel-mocks
rspec-rails
rspec-rebound
rspectre
rswag-api
rswag-specs
@@ -857,7 +834,7 @@ DEPENDENCIES
xmlrpc
RUBY VERSION
ruby 3.3.8p144
ruby 3.3.7p123
BUNDLED WITH
2.4.22

View File

@@ -1,6 +1,7 @@
# 🌱 Growstuff
![Build status](https://github.com/Growstuff/growstuff/workflows/CI/badge.svg)
[![Code Climate](https://codeclimate.com/github/Growstuff/growstuff/badges/gpa.svg)](https://codeclimate.com/github/Growstuff/growstuff)
Welcome to the Growstuff project.

View File

@@ -30,7 +30,3 @@
@import "predictions";
@import "homepage";
@import "maps";
@view-transition {
navigation: auto;
}

View File

@@ -24,6 +24,9 @@ class ActivitiesController < DataController
end
def show
# @activity is loaded by load_and_authorize_resource.
# We need to ensure comments are eager-loaded.
@activity = Activity.includes(comments: :author).find(params[:id])
respond_with @activity
end

View File

@@ -13,43 +13,66 @@ class CommentsController < ApplicationController
end
def new
@comment = Comment.new
@post = Post.find_by(id: params[:post_id])
if @post
@comments = @post.comments
respond_with(@comments)
@commentable = find_commentable
if @commentable
@comment = @commentable.comments.new
@comments = @commentable.comments.post_order # Assuming post_order is generic enough or will be adapted
respond_with(@comment) # Changed from @comments to @comment, or @commentable
else
redirect_to(request.referer || root_url,
alert: "Can't post a comment on a non-existent post")
alert: "Cannot add a comment to a non-existent or unspecified item.")
end
end
def edit
@comments = @comment.post.comments
# @comment is loaded by load_and_authorize_resource
@comments = @comment.commentable.comments.post_order # Assuming post_order is generic
end
def create
@comment = Comment.new(comment_params)
@comment.author = current_member
@comment.save
respond_with @comment, location: @comment.post
@commentable = find_commentable
if @commentable
@comment = @commentable.comments.new(comment_params)
@comment.author = current_member
@comment.save
respond_with @comment, location: @comment.commentable # Redirect to the commentable parent
else
redirect_to(request.referer || root_url,
alert: "Cannot create comment for a non-existent or unspecified item.")
end
end
def update
@comment.update(body: comment_params['body'])
respond_with @comment, location: @comment.post
# @comment is loaded by load_and_authorize_resource
@comment.update(comment_params) # body is permitted by comment_params
respond_with @comment, location: @comment.commentable # Redirect to the commentable parent
end
def destroy
@post = @comment.post
# @comment is loaded by load_and_authorize_resource
@commentable = @comment.commentable # Store before destroying
@comment.destroy
respond_with(@post)
respond_with @comment, location: @commentable # Redirect to the commentable parent
end
private
def find_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
model_name = $1.classify
# Ensure model_name is one of the expected commentable types
# to prevent arbitrary model lookups.
allowed_commentables = %w[Post Photo Planting Harvest Activity]
if allowed_commentables.include?(model_name)
return model_name.constantize.find_by(id: value)
end
end
end
nil
end
def comment_params
params.require(:comment).permit(:body, :post_id)
params.require(:comment).permit(:body) # Removed post_id
end
end

View File

@@ -75,7 +75,6 @@ class CropsController < ApplicationController
end
def show
@problems = Problem.joins(plantings: :crop).where(crops: { id: @crop.id }).distinct
respond_to do |format|
format.html do
@posts = @crop.posts.order(created_at: :desc).paginate(page: params[:page])

View File

@@ -32,6 +32,9 @@ class HarvestsController < DataController
end
def show
# @harvest is loaded by load_and_authorize_resource.
# We need to ensure comments are eager-loaded.
@harvest = Harvest.includes(comments: :author).find(params[:id])
@matching_plantings = matching_plantings if @harvest.owner == current_member
@photos = @harvest.photos.order(created_at: :desc).paginate(page: params[:page])
respond_with(@harvest)

View File

@@ -20,6 +20,9 @@ class PhotosController < ApplicationController
end
def show
# @photo is loaded by load_and_authorize_resource.
# We need to ensure comments are eager-loaded.
@photo = Photo.includes(comments: :author).find(params[:id])
@crops = Crop.distinct.joins(:photo_associations).where(photo_associations: { photo: @photo })
respond_with(@photo)
end

View File

@@ -34,6 +34,9 @@ class PlantingsController < DataController
end
def show
# @planting is loaded by load_and_authorize_resource.
# We need to ensure comments are eager-loaded.
@planting = Planting.includes(comments: :author).find(params[:id])
@photos = @planting.photos.includes(:owner).order(date_taken: :desc)
@harvests = Harvest.search(where: { planting_id: @planting.id })
@current_activities = @planting.activities.current.includes(:owner).order(created_at: :desc)
@@ -107,7 +110,7 @@ class PlantingsController < DataController
:crop_id, :description, :garden_id, :planted_at,
:parent_seed_id,
:quantity, :sunniness, :planted_from, :finished,
:finished_at, :failed, problem_ids: []
:finished_at
)
end

View File

@@ -1,76 +0,0 @@
# frozen_string_literal: true
class ProblemsController < ApplicationController
before_action :authenticate_member!, except: %i(index show)
load_and_authorize_resource id_param: :slug, class: Problem
respond_to :html, :json
def index
@problems = Problem.approved.popular.paginate(page: params[:page])
@num_requested_problems = requested_problems.size if current_member
respond_with @problems
end
def requested
@requested = requested_problems.paginate(page: params[:page])
respond_with @requested
end
def show
@problem = Problem.friendly.find(params[:id])
@plantings = @problem.plantings.paginate(page: params[:page])
respond_with @problem
end
def new
@problem = Problem.new
respond_with @problem
end
def edit; end
def create
@problem = Problem.new(problem_params)
if current_member.role? :problem_wrangler
@problem.creator = current_member
else
@problem.requester = current_member
@problem.approval_status = "pending"
end
@problem.save
respond_with @problem
end
def update
if can?(:wrangle, @problem)
@problem.approval_status = 'rejected' if params.fetch("reject", false)
@problem.approval_status = 'approved' if params.fetch("approve", false)
end
@problem.update(problem_params)
respond_with @problem
end
def wrangle
@approval_status = params[:approval_status]
@problems = case @approval_status
when "pending"
Problem.pending_approval
when "rejected"
Problem.rejected
else
Problem.recent
end.paginate(page: params[:page])
@problem_wranglers = Role.problem_wranglers
respond_with @problems
end
private
def problem_params
params.require(:problem).permit(:name, :reason_for_rejection, :rejection_notes)
end
def requested_problems
current_member.requested_problems.pending_approval
end
end

View File

@@ -19,10 +19,6 @@ class SeedsController < DataController
where['parent_planting'] = @planting.id
end
if params[:tradeable_to].present?
where['tradeable_to'] = params[:tradeable_to]
end
@show_all = (params[:all] == '1')
where['finished'] = false unless @show_all

View File

@@ -32,7 +32,7 @@ module ApplicationHelper
# of HAML, Tilt, and dynamic compilation with interpolated ruby.
def markdownify(text)
translator = Haml::Filters::GrowstuffMarkdown.new
translator.expand_members!(translator.expand_problems!(translator.expand_crops!(text.to_s)))
translator.expand_members!(translator.expand_crops!(text.to_s))
end
#

View File

@@ -34,8 +34,6 @@ class Ability
# are wranglers or admins
cannot :read, Crop
can :read, Crop, approval_status: "approved"
cannot :read, Problem
can :read, Problem, approval_status: "approved"
# scientific names should only be viewable if associated crop is approved
cannot :read, ScientificName
can :read, ScientificName do |sn|
@@ -58,8 +56,6 @@ class Ability
# members can see even rejected or pending crops if they requested it
can :read, Crop, requester_id: member.id
can :requested, Crop # see list of crops they've requested
can :read, Problem, requester_id: member.id
can :requested, Problem
# managing your own user settings
can :update, Member, id: member.id
@@ -86,14 +82,8 @@ class Ability
can :gbif, Crop
end
if member.role? :problem_wrangler
can :wrangle, Problem
can :manage, Problem
end
# any member can create a crop provisionally
can :create, Crop
can :create, Problem
# can create & destroy their own authentications against other sites.
can :create, Authentication
@@ -108,7 +98,19 @@ class Ability
can :destroy, Like, member_id: member.id
can :create, Comment
can :update, Comment, author_id: member.id
can :destroy, Comment, author_id: member.id
can :destroy, Comment do |comment|
is_author = comment.author_id == member.id
is_commentable_owner = false
if comment.commentable.present?
if comment.commentable.respond_to?(:owner_id) && comment.commentable.owner_id == member.id
is_commentable_owner = true
# Posts use author_id for their "owner"
elsif comment.commentable.respond_to?(:author_id) && comment.commentable.author_id == member.id
is_commentable_owner = true
end
end
is_author || is_commentable_owner
end
# same deal for gardens and plantings
can :create, Garden

View File

@@ -2,26 +2,31 @@
class Comment < ApplicationRecord
belongs_to :author, class_name: 'Member', inverse_of: :comments
belongs_to :post, counter_cache: true
belongs_to :commentable, polymorphic: true, counter_cache: true
scope :post_order, -> { order(created_at: :asc) } # for display on post page
after_create do
recipient = post.author.id
recipient = if commentable.respond_to?(:author)
commentable.author.id
elsif commentable.respond_to?(:owner)
commentable.owner.id
end
sender = author.id
# don't send notifications to yourself
if recipient != sender
if recipient && recipient != sender
Notification.create(
recipient_id: recipient,
sender_id: sender,
subject: "#{author} commented on #{post.subject}",
subject: "#{author} commented on your #{commentable.class.name.downcase}",
body:,
post_id: post.id
commentable_id: commentable.id,
commentable_type: commentable.class.name
)
end
end
def to_s
"#{author.login_name} commented on #{post.subject}"
"#{author.login_name} commented on #{commentable.class.name.downcase} ##{commentable.id}"
end
end

View File

@@ -17,7 +17,6 @@ class Crop < ApplicationRecord
has_many :scientific_names, dependent: :delete_all
has_many :alternate_names, dependent: :delete_all
has_many :plantings, dependent: :destroy
has_many :problems, through: :plantings
has_many :seeds, dependent: :destroy
has_many :harvests, dependent: :destroy
has_many :photo_associations, dependent: :delete_all, inverse_of: :crop

View File

@@ -42,10 +42,6 @@ class Member < ApplicationRecord
inverse_of: :requester
has_many :created_crops, class_name: 'Crop', foreign_key: 'creator_id', dependent: :nullify,
inverse_of: :creator
has_many :requested_problems, class_name: 'Problem', foreign_key: 'requester_id', dependent: :nullify,
inverse_of: :requester
has_many :created_problems, class_name: 'Problem', foreign_key: 'creator_id', dependent: :nullify,
inverse_of: :creator
has_many :created_alternate_names, class_name: 'AlternateName', foreign_key: 'creator_id', inverse_of: :creator
has_many :created_scientific_names, class_name: 'ScientificName', foreign_key: 'creator_id', inverse_of: :creator

View File

@@ -3,7 +3,7 @@
class Notification < ApplicationRecord
belongs_to :sender, class_name: 'Member', inverse_of: :sent_notifications
belongs_to :recipient, class_name: 'Member', inverse_of: :notifications
belongs_to :post, optional: true
belongs_to :commentable, polymorphic: true, optional: true
validates :subject, length: { maximum: 255 }

View File

@@ -24,8 +24,6 @@ class Planting < ApplicationRecord
belongs_to :crop, counter_cache: true
has_many :harvests, dependent: :destroy
has_many :activities, dependent: :destroy
has_many :planting_problems, dependent: :destroy
has_many :problems, through: :planting_problems
#
# Ancestry of food

View File

@@ -1,8 +0,0 @@
# frozen_string_literal: true
class PlantingProblem < ApplicationRecord
include PhotoCapable
belongs_to :planting
belongs_to :problem
end

View File

@@ -13,14 +13,11 @@ class Post < ApplicationRecord
has_many :comments, dependent: :destroy
has_many :crop_posts, dependent: :delete_all
has_many :crops, through: :crop_posts
has_many :problem_posts, dependent: :delete_all
has_many :problems, through: :problem_posts
after_create :send_notification
#
# Triggers
after_save :update_crop_posts_association
after_save :update_problem_posts_association
default_scope { joins(:author).merge(Member.kept) } # Ensures the owner still exists
@@ -78,17 +75,6 @@ class Post < ApplicationRecord
end
end
def update_problem_posts_association
problems.clear
# look for problems mentioned in the post. eg. [aphids](problem)
body.scan(Haml::Filters::GrowstuffMarkdown::PROBLEM_REGEX) do |_m|
problem_name = Regexp.last_match(1)
problem = Problem.case_insensitive_name(problem_name).first
# create association
problems << problem if problem && problems.exclude?(problem)
end
end
def send_notification
recipients = []
sender = author.id

View File

@@ -1,88 +0,0 @@
# frozen_string_literal: true
class Problem < ApplicationRecord
extend FriendlyId
include PhotoCapable
include SearchCrops # Note: This might need to be adapted to SearchProblems
friendly_id :name, use: %i(slugged finders)
##
## Relationships
belongs_to :creator, class_name: 'Member', optional: true, inverse_of: :created_problems
belongs_to :requester, class_name: 'Member', optional: true, inverse_of: :requested_problems
has_many :planting_problems, dependent: :delete_all
has_many :plantings, through: :planting_problems
has_many :problem_posts, dependent: :delete_all
has_many :posts, through: :problem_posts, dependent: :delete_all
##
## Scopes
scope :recent, -> { approved.order(created_at: :desc) }
scope :popular, -> { approved.order(Arel.sql("plantings_count desc, lower(name) asc")) }
scope :pending_approval, -> { where(approval_status: "pending") }
scope :approved, -> { where(approval_status: "approved") }
scope :rejected, -> { where(approval_status: "rejected") }
scope :interesting, -> { approved.has_photos }
scope :has_photos, -> { includes(:photos).where.not(photos: { id: nil }) }
##
## Validations
validates :reason_for_rejection, presence: true, if: :rejected?
validate :must_be_rejected_if_rejected_reasons_present
validate :must_have_meaningful_reason_for_rejection
validates :name, uniqueness: { scope: :approval_status }, if: :pending?
def to_s
name
end
def to_param
slug
end
def pending?
approval_status == "pending"
end
def approved?
approval_status == "approved"
end
def rejected?
approval_status == "rejected"
end
def approval_statuses
%w(rejected pending approved)
end
def reasons_for_rejection
["already in database", "not a pest or disease", "not enough information", "other"]
end
def rejection_explanation
return rejection_notes if reason_for_rejection == "other"
reason_for_rejection
end
def self.case_insensitive_name(name)
where(["lower(problems.name) = :value", { value: name.downcase }])
end
private
def must_be_rejected_if_rejected_reasons_present
return if rejected?
return unless reason_for_rejection.present? || rejection_notes.present?
errors.add(:approval_status, "must be rejected if a reason for rejection is present")
end
def must_have_meaningful_reason_for_rejection
return unless reason_for_rejection == "other" && rejection_notes.blank?
errors.add(:rejection_notes, "must be added if the reason for rejection is \"other\"")
end
end

View File

@@ -1,6 +0,0 @@
# frozen_string_literal: true
class ProblemPost < ApplicationRecord
belongs_to :problem
belongs_to :post
end

View File

@@ -8,7 +8,7 @@ class Role < ApplicationRecord
has_and_belongs_to_many :members
class << self
%i(crop_wranglers admins problem_wranglers).each do |method|
%i(crop_wranglers admins).each do |method|
define_method method do
slug = method.to_s.singularize.dasherize
Role.where(slug:).try(:first).try(:members)

View File

@@ -44,5 +44,8 @@
%a{name: 'plantings'}
= render 'plantings/card', planting: @activity.planting
%section.comments.mt-4
= render 'comments/comments', commentable: @activity
.col-md-4.col-xs-12

View File

@@ -0,0 +1,21 @@
.comments-section.mt-4
%h4.mb-3 Comments
- if commentable.comments.any?
.list-group
- commentable.comments.post_order.each do |comment|
.list-group-item.p-0.mb-2.border-0
= render 'comments/comment', comment: comment
- else
%p No comments yet.
- if can? :create, Comment # Assuming a general ability to create comments
.mt-3
= link_to "Add Comment", new_polymorphic_path([commentable, Comment.new]), class: 'btn btn-primary'
%hr/
-# This section is for rendering the new/edit form directly on the page if needed,
-# but the primary "Add Comment" link above goes to the comments/new page.
-# If @new_comment is passed, it means we want to show the form.
- if defined?(@new_comment) && @new_comment && can?(:create, Comment) # Check @new_comment specifically
%h5.mt-3 Leave a comment
= render 'comments/form', commentable: commentable, comment: @new_comment

View File

@@ -3,14 +3,14 @@
- if content_for? :title
%h1.h2-responsive.text-center
%strong=yield :title
= form_for(@comment, html: { class: "form-horizontal" }) do |f|
- if @comment.errors.any?
= form_for(commentable ? [commentable, comment] : comment, html: { class: "form-horizontal" }) do |f|
- if comment.errors.any?
#error_explanation
%h2
= pluralize(@comment.errors.size, "error")
= pluralize(comment.errors.size, "error")
prohibited this comment from being saved:
%ul
- @comment.errors.full_messages.each do |msg|
- comment.errors.full_messages.each do |msg|
%li= msg
.md-form
@@ -21,6 +21,3 @@
= render partial: "shared/markdown_help"
.actions.text-right
= f.submit 'Post comment', class: 'btn btn-primary'
- if defined?(@post)
.field
= f.hidden_field :post_id, value: @post.id

View File

@@ -1,7 +1,2 @@
= content_for :title, "Editing comment"
%p
Editing comment on
= link_to @comment.post.subject, @comment.post
= render 'form'
%h2 Edit Comment
= render 'comments/form', commentable: @comment.commentable, comment: @comment

View File

@@ -1,11 +1,5 @@
= content_for :title, "New comment"
%h2
Add comment to
= @commentable.class.name.downcase
%section.blog-post
.card.post{ id: "post-#{@post.id}" }
.card-header
%h2.display-3= @post.subject
.card-body= render "posts/single", post: @post || @comment.post, subject: true
= render partial: "posts/comments", locals: { post: @post || @comment.post }
= render 'form'
= render 'comments/form', commentable: @commentable, comment: @comment

View File

@@ -3,3 +3,4 @@
There are
= link_to "https://openfarm.cc/en/crops/#{CGI.escape @crop.name.gsub(' ', '-').downcase}" do
#{crop.guides_count} growing guides on Open Farm

View File

@@ -30,15 +30,6 @@
- @crop.companions.each do |companion|
= render 'crops/tiny', crop: companion
- if @problems.any?
%section.problems
%h2 Problems
- @problems.group_by(&:name).each do |problem_name, problems|
- problem = problems.first
= link_to problem_path(problem) do
= problem_name
%span.badge.badge-secondary= problems.size
%section.photos
= cute_icon
= render 'crops/photos', crop: @crop

View File

@@ -66,5 +66,8 @@
Havested from
= link_to @harvest.planting, @harvest.planting
%section.comments.mt-4
= render 'comments/comments', commentable: @harvest
.col-md-4.col-xs-12
= render @harvest.crop

View File

@@ -5,3 +5,5 @@
number_crops: link_to(t('.number_crops_linktext', count: Crop.count.to_i), crops_path),
number_plantings: link_to(t('.number_plantings_linktext', count: Planting.count.to_i), plantings_path),
number_gardens: link_to(t('.number_gardens_linktext', count: Garden.count.to_i), gardens_path))

View File

@@ -51,8 +51,7 @@
%section.seeds
= cute_icon
= render 'seeds'
%p.text-right
= link_to "#{t('home.seeds.view_all')} »", seeds_path(tradeable_to: ['locally', 'nationally', 'internationally']), class: 'btn btn-block'
%p.text-right= link_to "#{t('home.seeds.view_all')} »", seeds_path, class: 'btn btn-block'
.col-12.col-lg-6
%section.discussion.text-center
= cute_icon

View File

@@ -46,4 +46,8 @@
- else
= @photo.license_name
= render "associations", photo: @photo
= render "associations", photo: @photo
.row
.col-md-9
= render 'comments/comments', commentable: @photo

View File

@@ -47,11 +47,6 @@
= f.number_field :quantity, label: 'How many?', min: 1
= f.text_area :description, rows: 6, label: 'Tell us more about it'
= f.collection_check_boxes :problem_ids, Problem.approved.order(:name), :id, :name do |b|
.form-check
= b.check_box
= b.label
.row
.col-md-6
= f.check_box :finished, label: 'Mark as finished'

View File

@@ -51,23 +51,6 @@
.col-md-8.col-xs-12
%section= render 'facts', planting: @planting
- if @planting.problems.any?
%section.problems
%h2 Problems
- @planting.planting_problems.each do |planting_problem|
.card
.card-header
%h3= planting_problem.problem.name
.card-body
- if planting_problem.photos.any?
.row
- planting_problem.photos.each do |photo|
.col-md-4
= image_tag photo.thumbnail_url, class: 'img-fluid'
- else
%p No photos of this problem for this planting yet.
- if @planting.description.present?
= cute_icon
.card
@@ -96,6 +79,9 @@
.col-md-12
%p Nothing is currently planned here.
%section.comments.mt-4
= render 'comments/comments', commentable: @planting
.col-md-4.col-xs-12
= render @planting.crop

View File

@@ -9,3 +9,4 @@
- else
%h2 There are no comments yet

View File

@@ -22,10 +22,6 @@
= render "shared/signin_signup",
to: "or to start using #{ENV['GROWSTUFF_SITE_NAME']} to track what you're planting and harvesting"
- content_for :buttonbar do
- if @post.comments.count > 10 && can?(:create, Comment)
= link_to 'Comment', new_comment_path(post_id: @post.id), class: 'btn'
- content_for :breadcrumbs do
%li.breadcrumb-item= link_to @post.author, @post.author
%li.breadcrumb-item= link_to 'posts', member_posts_path(member_slug: @post.author.slug)
@@ -47,13 +43,10 @@
.card-footer
= render 'likes/likes', object: @post
.float-right
- if can? :create, Comment
= link_to new_comment_path(post_id: @post.id), class: 'btn' do
= icon 'fas', 'comment'
Comment
-# Link removed as it's now part of the _comments partial
%section.comments
= render "comments", post: @post
= render 'comments/comments', commentable: @post
.col-md-4.col-12
= render @post.author

View File

@@ -1,54 +0,0 @@
= bootstrap_form_for(@problem) do |f|
- if @problem.errors.any?
#error_explanation.alert.alert-warning{role: "alert"}
%h3
= pluralize(@problem.errors.size, "error")
prohibited this problem from being saved:
%ul
- @problem.errors.full_messages.each do |msg|
%li= msg
.card.col-12.col-md-8.mx-auto.float-none.white
.card-header
- if content_for? :title
%h1.h2-responsive.text-center
%strong=yield :title
.card-body
- if can? :wrangle, @problem
%p
%span.help-block
As a problem wrangler, you can approve or reject problem suggestions.
%h2 Basic information
.form-group#new_problem
= f.text_field :name, required: true
%span.help-block
The common name for the problem, in English (required).
- if can? :wrangle, @problem
Wranglers: please ensure this is singular, and capitalize
proper nouns only.
- if (can?(:wrangle, @problem) && @problem.requester) || (cannot?(:wrangle, @problem) && @problem.new_record?)
%h2 Problem request notes
= f.text_area :request_notes, rows: 3, id: 'request_notes', label: 'Comments'
- unless can? :wrangle, @problem
%p
When you submit this form, your suggestion will be sent to our team of
volunteer problem wranglers for review. We'll let you know the outcome as soon as we can.
- if can?(:wrangle, @problem) && @problem.requester
= f.select(:reason_for_rejection, @problem.reasons_for_rejection, include_blank: true)
= f.text_area :rejection_notes, rows: 3
%span.help-block
Please provide additional notes why this problem request was rejected if the above reasons do not apply.
.card-footer
.text-right
- if @problem.approved?
= f.submit 'Save'
- else
= f.submit 'Reject', class: 'btn btn-danger', name: 'reject'
= f.submit 'Approve and save', class: 'btn btn-success', name: 'approve'

View File

@@ -1,10 +0,0 @@
- cache problem do
.card.problem-thumbnail
= link_to problem_path(id: problem.slug) do
= image_tag(problem.thumbnail_url.presence || placeholder_image,
alt: "Image of #{problem.name}",
class: 'img img-card')
.text
%h3.problem-name= link_to problem.name, problem_path(id: problem.slug)

View File

@@ -1,30 +0,0 @@
- content_for :title, "Edit problem: #{@problem.name}"
- if @problem.approval_status == "approved"
- if @problem.requester
%p
Requested by #{link_to @problem.requester, @problem.requester}
#{distance_of_time_in_words(@problem.created_at, Time.zone.now)} ago.
%p
Approved by #{link_to @problem.creator, @problem.creator}.
- else
%p
Added by
= link_to @problem.creator, @problem.creator
#{distance_of_time_in_words(@problem.created_at, Time.zone.now)} ago.
- elsif @problem.approval_status == "pending"
.alert.alert-danger
%p
Requested by #{link_to @problem.requester, @problem.requester}
#{distance_of_time_in_words(@problem.created_at, Time.zone.now)} ago.
%p
Status: #{@problem.approval_status}.
- elsif @problem.approval_status == "rejected"
.alert.alert-danger
%p
Requested by #{link_to @problem.requester, @problem.requester}
#{distance_of_time_in_words(@problem.created_at, Time.zone.now)} ago.
%p
Status: #{@problem.approval_status} by #{link_to @problem.creator, @problem.creator}.
= render 'form'

View File

@@ -1,13 +0,0 @@
- content_for :title, t('.title')
- content_for :breadcrumbs do
%li.breadcrumb-item.active= link_to 'Problems', problems_path
%section.problems
%h2= t('.title')
= will_paginate @problems
.index-cards
- @problems.each do |p|
= render 'problems/thumbnail', problem: p
= will_paginate @problems

View File

@@ -1,15 +0,0 @@
- content_for :title, (can?(:wrangle, @problem) ? "New problem" : "Suggest a problem")
- unless can? :wrangle, @problem
%p
Thanks for taking the time to suggest a problem! Our problem database is
managed by volunteers, and we appreciate your help. Here are some
things to consider when suggesting a new problem:
%ul
%li
First, you might want to search our problems
to make sure we don't have it already, perhaps under an alternate name.
%li
The Growstuff database only contains problems related to growing edible plants.
= render 'form'

View File

@@ -1,26 +0,0 @@
- content_for :title, @problem.name
- content_for :breadcrumbs do
%li.breadcrumb-item= link_to 'Problems', problems_path
%li.breadcrumb-item.active= link_to @problem.name.capitalize, @problem
.jumbotron
%h1= @problem.name
.row
.col-md-9
%section.plantings
%h2 Plantings with this problem
= will_paginate @plantings
.index-cards
- @plantings.each do |p|
= render 'plantings/thumbnail', planting: p
= will_paginate @plantings
.col-md-3
.card
.card-body
%h4.card-title= @problem.name
%p.card-text
This problem has been reported on
= pluralize(@problem.plantings.count, 'planting')
so far.

View File

@@ -1,51 +0,0 @@
- content_for :title, "Problem Wrangling"
%h1 Problem Wrangling
%nav.nav
= link_to "Add Problem", new_problem_path, class: 'btn'
%section.problem_wranglers
%h2 Problem Wranglers
- @problem_wranglers.each do |problem_wrangler|
= render 'members/tiny', member: problem_wrangler
%hr/
%section
%h2 Problems
%ul#myTab.nav.nav-tabs{role: "tablist"}
%li.nav-item
%a#home-tab.nav-link{ href: wrangle_problems_path, role: "tab", class: @approval_status.blank? ? 'active' : ''}
Recently added
%li.nav-item
%a#profile-tab.nav-link{ href: wrangle_problems_path(approval_status: "pending"), role: "tab", class: @approval_status == "pending" ? 'active' : ''}
Pending approval
%li.nav-item
%a#contact-tab.nav-link{ href: wrangle_problems_path(approval_status: "rejected"), role: "tab", class: @approval_status == "rejected" ? 'active' : ''} Rejected
%table.table.table-striped.table-bordered.table-sm{id: @approval_status.blank? ? 'recently-added-problems' : "#{@approval_status}-problems" }
%tr
%th Name
%th Requested by
- if @approval_status == "rejected"
%th Rejected by
- if @approval_status != "rejected" && @approval_status != "pending"
%th Added by
%th When
- @problems.each do |p|
%tr
%td
= link_to edit_problem_path(p) do
= icon 'fas', 'bug'
= p.name
%td= p.requester.present? ? (link_to p.requester, p.requester) : "N/A"
- unless @approval_status == "pending"
%td= p.creator.present? ? (link_to p.creator, p.creator) : "N/A"
%td
= distance_of_time_in_words(p.created_at, Time.zone.now)
ago.
= page_entries_info @problems
= will_paginate @problems

View File

@@ -17,14 +17,6 @@
= check_box_tag 'active', 'all', @show_all
include finished
%hr/
%section.filters
%h2 Tradeable
%ul.nav.flex-column
%li.nav-item= link_to "All tradable seeds", seeds_path(tradeable_to: ['locally', 'nationally', 'internationally'])
- Seed::TRADABLE_TO_VALUES.each do |value|
- unless value == 'nowhere'
%li.nav-item= link_to value.capitalize, seeds_path(tradeable_to: value)
%hr/
- if @owner
= render @owner
- if @crop

View File

@@ -5,7 +5,7 @@ Mailboxer.setup do |config|
config.uses_emails = true
# Configures the default from for emails sent for Messages and Notifications
config.default_from = "Growstuff <#{ENV.fetch('GROWSTUFF_EMAIL', "no-reply@growstuff.org")}>"
config.default_from = "no-reply@growstuff.org"
# Configures the methods needed by mailboxer
# config.email_method = :email

View File

@@ -1,7 +0,0 @@
en:
mailboxer:
message_mailer:
subject_new: "New Notification: %{subject}"
subject_reply: "New Reply: %{subject}"
notification_mailer:
subject: "New notification: %{subject}"

View File

@@ -28,13 +28,17 @@ Rails.application.routes.draw do
resources :photos, only: :index
end
concern :commentable do
resources :comments, only: [:new, :create, :edit, :update, :destroy], shallow: true
end
resources :gardens, concerns: :has_photos, param: :slug do
get 'timeline' => 'charts/gardens#timeline', constraints: { format: 'json' }
resources :garden_collaborators
end
resources :plantings, concerns: :has_photos, param: :slug do
resources :plantings, concerns: [:has_photos, :commentable], param: :slug do
resources :harvests
resources :seeds
collection do
@@ -47,11 +51,11 @@ Rails.application.routes.draw do
get 'crop/:crop' => 'seeds#index', as: 'seeds_by_crop', on: :collection
end
resources :harvests, concerns: :has_photos, param: :slug do
resources :harvests, concerns: [:has_photos, :commentable], param: :slug do
get 'crop/:crop' => 'harvests#index', as: 'harvests_by_crop', on: :collection
end
resources :posts do
resources :posts, concerns: :commentable do
get 'author/:author' => 'posts#index', as: 'by_author', on: :collection
end
@@ -62,7 +66,7 @@ Rails.application.routes.draw do
end
resources :alternate_names
resources :plant_parts
resources :photos
resources :photos, concerns: :commentable
resources :photo_associations, only: :destroy
@@ -89,13 +93,6 @@ Rails.application.routes.draw do
end
end
resources :problems, param: :slug do
collection do
get 'requested'
get 'wrangle'
end
end
resources :comments
resources :forums
@@ -119,7 +116,7 @@ Rails.application.routes.draw do
end
resources :messages
resources :activities, param: :slug
resources :activities, concerns: :commentable, param: :slug
resources :conversations do
collection do
delete 'destroy_multiple'

View File

@@ -1,22 +0,0 @@
# Hi there!
#
# This is a configuration file for the Crowdin CLI.
# You'll need to replace the placeholder project_id with your actual
# project ID from CrowdIn.
#
# For more information, see the Crowdin CLI documentation:
# https://support.crowdin.com/enterprise/cli-v3/
#
project_id: "your-project-id"
api_token_env: "CROWDIN_API_TOKEN"
base_path: "."
files:
- source: '/config/locales/en.yml'
translation: '/config/locales/%two_letters_code%.yml'
# The 'ignore' property is used to exclude files from processing.
# We are ignoring the existing Japanese translation file.
ignore:
- '/config/locales/ja.yml'
- source: '/config/locales/*.en.yml'
translation: '/config/locales/%file_name%.%two_letters_code%.yml'

View File

@@ -0,0 +1,32 @@
class AddCommentableToComments < ActiveRecord::Migration[6.0]
def up
add_column :comments, :commentable_id, :integer
add_column :comments, :commentable_type, :string
add_index :comments, [:commentable_type, :commentable_id]
# Data migration
execute <<-SQL
UPDATE comments
SET commentable_id = post_id,
commentable_type = 'Post'
WHERE post_id IS NOT NULL;
SQL
remove_column :comments, :post_id
end
def down
add_column :comments, :post_id, :integer
# Data migration back
execute <<-SQL
UPDATE comments
SET post_id = commentable_id
WHERE commentable_type = 'Post';
SQL
remove_index :comments, [:commentable_type, :commentable_id]
remove_column :comments, :commentable_type
remove_column :comments, :commentable_id
end
end

View File

@@ -4,7 +4,6 @@
class Haml::Filters
class GrowstuffMarkdown
CROP_REGEX = /(?<!\\)\[([^\[\]]+?)\]\(crop\)/
PROBLEM_REGEX = /(?<!\\)\[([^\[\]]+?)\]\(problem\)/
MEMBER_REGEX = /(?<!\\)\[([^\[\]]+?)\]\(member\)/
MEMBER_AT_REGEX = /(?<!\\)(@\w+)/
MEMBER_ESCAPE_AT_REGEX = /(?<!\\)\\(?=@\w+)/
@@ -43,25 +42,6 @@ class Haml::Filters
end
end
def expand_problems!(text)
# turn [aphids](problem) into [aphids](http://growstuff.org/problems/aphids)
text.gsub(PROBLEM_REGEX) do
problem_str = Regexp.last_match(1)
# find problem case-insensitively
problem = Problem.where('lower(name) = ?', problem_str.downcase).first
problem_link problem, problem_str
end
end
def problem_link(problem, link_text)
if problem
url = Rails.application.routes.url_helpers.problem_url(problem, only_path: true)
"[#{link_text}](#{url})"
else
link_text
end
end
def crop_link(crop, link_text)
if crop
url = Rails.application.routes.url_helpers.crop_url(crop, only_path: true)

View File

@@ -8,18 +8,4 @@ namespace :openfarm do
Rails.logger = Logger.new(STDOUT)
OpenfarmService.new.import!
end
desc "Delete all pictures with source OpenFarm"
task delete_pictures: :environment do
puts "Deleting pictures with source OpenFarm..."
photos_to_delete = Photo.where(source: 'openfarm')
count = photos_to_delete.count
photos_to_delete.each do |photo|
photo.associations.each do |photo_association|
photo_association.delete
end
photo.delete
end
puts "Deleted #{count} pictures."
end
end

View File

@@ -31,95 +31,316 @@ describe CommentsController do
end
end
describe "GET new" do
let(:post) { FactoryBot.create(:post) }
describe "with valid params" do
before { get :new, params: { post_id: post.id } }
let(:old_comment) { FactoryBot.create(:comment, post:) }
it "picks up post from params" do
expect(assigns(:post)).to eq(post)
end
it "assigns the old comments as @comments" do
expect(assigns(:comments)).to eq [old_comment]
# Shared examples for commentable controllers
RSpec.shared_examples "a commentable controller" do |commentable_factory_name, commentable_param_key|
let(:commentable_owner) { FactoryBot.create(:member) }
let(:comment_author) { FactoryBot.create(:member) }
let(:admin_user) { FactoryBot.create(:member, :admin) }
let!(:commentable) do
if [:post].include?(commentable_factory_name)
FactoryBot.create(commentable_factory_name, author: commentable_owner)
else
FactoryBot.create(commentable_factory_name, owner: commentable_owner)
end
end
it "dies if no post specified" do
get :new
expect(response).not_to be_successful
end
end
describe "GET #new" do
context "when not logged in" do
before { sign_out member }
it "redirects to login" do
get :new, params: { commentable_param_key => commentable.id }
expect(response).to redirect_to(new_member_session_path)
end
end
describe "GET edit" do
let(:post) { FactoryBot.create(:post) }
context "when logged in" do
before { sign_in comment_author }
it "assigns @commentable and new @comment" do
get :new, params: { commentable_param_key => commentable.id }
expect(assigns(:commentable)).to eq(commentable)
expect(assigns(:comment)).to be_a_new(Comment)
expect(response).to render_template(:new)
end
before { get :edit, params: { id: comment.to_param } }
describe "my comment" do
let!(:comment) { FactoryBot.create(:comment, author: member, post:) }
let!(:old_comment) { FactoryBot.create(:comment, post:, created_at: Time.zone.yesterday) }
it "assigns previous comments as @comments" do
expect(assigns(:comments)).to eq([comment, old_comment])
it "redirects if commentable not found" do
get :new, params: { commentable_param_key => -1 }
expect(response).to redirect_to(request.referer || root_url)
expect(flash[:alert]).to match(/Cannot add a comment to a non-existent or unspecified item/)
end
end
end
describe "not my comment" do
let(:comment) { FactoryBot.create(:comment, post:) }
describe "POST #create" do
let(:valid_comment_params) { { body: "This is a great comment." } }
let(:invalid_comment_params) { { body: "" } }
it { expect(response).not_to be_successful }
end
end
context "when not logged in" do
before { sign_out member }
it "redirects to login" do
post :create, params: { commentable_param_key => commentable.id, comment: valid_comment_params }
expect(response).to redirect_to(new_member_session_path)
end
end
describe "PUT update" do
before { put :update, params: { id: comment.to_param, comment: valid_attributes } }
context "when logged in" do
before { sign_in comment_author }
describe "my comment" do
let(:comment) { FactoryBot.create(:comment, author: member) }
context "with valid params" do
it "creates a new Comment" do
expect {
post :create, params: { commentable_param_key => commentable.id, comment: valid_comment_params }
}.to change(Comment, :count).by(1)
end
it "redirects to the comment's post" do
expect(response).to redirect_to(comment.post)
it "assigns the comment's author to current_member" do
post :create, params: { commentable_param_key => commentable.id, comment: valid_comment_params }
expect(Comment.last.author).to eq(comment_author)
end
it "redirects to the commentable's show page" do
post :create, params: { commentable_param_key => commentable.id, comment: valid_comment_params }
expect(response).to redirect_to(commentable)
end
end
context "with invalid params" do
it "does not create a comment" do
expect {
post :create, params: { commentable_param_key => commentable.id, comment: invalid_comment_params }
}.not_to change(Comment, :count)
end
it "re-renders the 'new' template (or commentable show with errors)" do
# The controller currently redirects if commentable is not found in create,
# but for invalid comment params, it should re-render or show errors.
# The current controller's create action saves and then responds.
# If save fails, it typically re-renders the form via respond_with.
# For this test, we'll assume it re-renders 'new' if save fails.
# A more precise test would check the response if @comment.save fails.
# For now, we'll check that it doesn't redirect to the commentable if save fails.
post :create, params: { commentable_param_key => commentable.id, comment: invalid_comment_params }
# Depending on how `respond_with` handles failure for new comment on commentable,
# it might render the commentable's show page or the comments/new template.
# The key is that it shouldn't be a successful redirect to the commentable.
# And @comment.errors should be present.
expect(assigns(:comment).errors).not_to be_empty
# Check for re-render of new or specific error handling view
# For now, checking that it's not a successful redirect if save fails.
# This might need adjustment based on actual controller error flow.
# A common pattern is to render the 'new' template again or the parent's show page.
# The `respond_with @comment, location: @comment.commentable` will try to redirect if valid.
# If invalid, it should re-render the action that led to the form.
# For `create` failing, it's often the `new` view or the parent resource's view.
# The controller has `respond_with @comment, location: @comment.commentable`.
# If `@comment` is not persisted, `respond_with` might render the `new` template by convention,
# or the template of the action (`create.js.erb` or `create.html.erb` if they exist).
# Given the setup, it's likely to re-render 'new' or the controller action's default.
# Let's assume for now the form is on the `new` page.
# This is a weak assertion. A better one would be to check for `render_template(:new)`
# if the controller is set up to do that on failure.
# However, `respond_with` is tricky. It might also render the `commentable` show page with errors.
# The `new` action in controller renders `respond_with(@comment)`.
# The `create` action has `respond_with @comment, location: @comment.commentable`.
# If `@comment.save` fails, `respond_with` will typically render the `new` template by default
# if `create.html.haml` doesn't exist, or it might try to render `commentable` show page
# with errors displayed by the form partial.
# Given the form is rendered via `comments/new`, let's assume it re-renders new.
# This part of the test may need refinement based on actual error rendering flow.
# A simple check: ensure it doesn't redirect to the commentable.
expect(response).not_to redirect_to(commentable_path(commentable))
# And that @commentable is still assigned for the form.
expect(assigns(:commentable)).to eq(commentable)
end
end
it "redirects if commentable not found" do
post :create, params: { commentable_param_key => -1, comment: valid_comment_params }
expect(response).to redirect_to(request.referer || root_url)
expect(flash[:alert]).to match(/Cannot create comment for a non-existent or unspecified item/)
end
end
end
describe "not my comment" do
let(:comment) { FactoryBot.create(:comment) }
describe "GET #edit" do
let!(:comment) { FactoryBot.create(:comment, commentable: commentable, author: comment_author) }
it { expect(response).not_to be_successful }
context "when not logged in" do
before { sign_out member }
it "redirects to login" do
get :edit, params: { id: comment.id }
expect(response).to redirect_to(new_member_session_path)
end
end
context "as comment author" do
before { sign_in comment_author }
it "assigns @comment and renders edit" do
get :edit, params: { id: comment.id }
expect(assigns(:comment)).to eq(comment)
expect(response).to render_template(:edit)
end
end
context "as admin" do
before { sign_in admin_user }
it "assigns @comment and renders edit" do
get :edit, params: { id: comment.id }
expect(assigns(:comment)).to eq(comment)
expect(response).to render_template(:edit)
end
end
context "as unauthorized user" do
let(:other_user) { FactoryBot.create(:member) }
before { sign_in other_user }
it "redirects or shows error" do
get :edit, params: { id: comment.id }
expect(response).to redirect_to(root_url) # Or some other unauthorized path
expect(flash[:alert]).to match(/You are not authorized to access this page./)
end
end
end
describe "attempting to change post_id" do
let(:post) { FactoryBot.create(:post, subject: 'our post') }
let(:other_post) { FactoryBot.create(:post, subject: 'the other post') }
let(:valid_attributes) { { post_id: other_post.id, body: "kōrero" } }
let(:comment) { FactoryBot.create(:comment, author: member, post:) }
describe "PUT #update" do
let!(:comment) { FactoryBot.create(:comment, commentable: commentable, author: comment_author, body: "Original body") }
let(:updated_body) { "Updated comment body." }
it "does not change post_id" do
comment.reload
expect(comment.post_id).to eq(post.id)
context "when not logged in" do
before { sign_out member }
it "redirects to login" do
put :update, params: { id: comment.id, comment: { body: updated_body } }
expect(response).to redirect_to(new_member_session_path)
end
end
context "as comment author" do
before { sign_in comment_author }
context "with valid params" do
it "updates the comment" do
put :update, params: { id: comment.id, comment: { body: updated_body } }
comment.reload
expect(comment.body).to eq(updated_body)
end
it "redirects to commentable show page" do
put :update, params: { id: comment.id, comment: { body: updated_body } }
expect(response).to redirect_to(commentable_path(commentable))
end
end
context "with invalid params (empty body)" do
it "does not update the comment and re-renders edit" do
put :update, params: { id: comment.id, comment: { body: "" } }
comment.reload
expect(comment.body).to eq("Original body") # Should not change
expect(response).to render_template(:edit)
end
end
end
context "as admin" do
before { sign_in admin_user }
it "updates the comment" do
put :update, params: { id: comment.id, comment: { body: updated_body } }
comment.reload
expect(comment.body).to eq(updated_body)
expect(response).to redirect_to(commentable_path(commentable))
end
end
context "as unauthorized user" do
let(:other_user) { FactoryBot.create(:member) }
before { sign_in other_user }
it "redirects or shows error" do
put :update, params: { id: comment.id, comment: { body: updated_body } }
expect(response).to redirect_to(root_url)
expect(flash[:alert]).to match(/You are not authorized to access this page./)
end
end
end
describe "DELETE #destroy" do
let!(:comment_to_delete) { FactoryBot.create(:comment, commentable: commentable, author: comment_author) }
context "when not logged in" do
before { sign_out member }
it "redirects to login" do
delete :destroy, params: { id: comment_to_delete.id }
expect(response).to redirect_to(new_member_session_path)
end
end
context "as comment author" do
before { sign_in comment_author }
it "deletes the comment" do
expect {
delete :destroy, params: { id: comment_to_delete.id }
}.to change(Comment, :count).by(-1)
end
it "redirects to commentable show page" do
delete :destroy, params: { id: comment_to_delete.id }
expect(response).to redirect_to(commentable_path(commentable))
end
end
context "as commentable owner" do
before { sign_in commentable_owner }
it "deletes the comment" do
# Ensure comment_author is not the same as commentable_owner for this test case
expect(comment_to_delete.author).not_to eq(commentable_owner)
expect {
delete :destroy, params: { id: comment_to_delete.id }
}.to change(Comment, :count).by(-1)
end
it "redirects to commentable show page" do
delete :destroy, params: { id: comment_to_delete.id }
expect(response).to redirect_to(commentable_path(commentable))
end
end
context "as admin" do
before { sign_in admin_user }
it "deletes the comment" do
expect {
delete :destroy, params: { id: comment_to_delete.id }
}.to change(Comment, :count).by(-1)
end
it "redirects to commentable show page" do
delete :destroy, params: { id: comment_to_delete.id }
expect(response).to redirect_to(commentable_path(commentable))
end
end
context "as unauthorized user" do
let(:other_user) { FactoryBot.create(:member) }
before { sign_in other_user }
it "does not delete the comment and redirects or shows error" do
expect {
delete :destroy, params: { id: comment_to_delete.id }
}.not_to change(Comment, :count)
expect(response).to redirect_to(root_url)
expect(flash[:alert]).to match(/You are not authorized to access this page./)
end
end
end
end
describe "DELETE destroy" do
before { delete :destroy, params: { id: comment.to_param } }
# Apply shared examples for each commentable type
context "for Post" do
it_behaves_like "a commentable controller", :post, :post_id
end
describe "my comment" do
let(:comment) { FactoryBot.create(:comment, author: member) }
context "for Photo" do
it_behaves_like "a commentable controller", :photo, :photo_id
end
it "redirects to the post the comment was on" do
expect(response).to redirect_to(comment.post)
end
end
context "for Planting" do
it_behaves_like "a commentable controller", :planting, :planting_id
end
describe "not my comment" do
let(:comment) { FactoryBot.create(:comment) }
context "for Harvest" do
it_behaves_like "a commentable controller", :harvest, :harvest_id
end
it { expect(response).not_to be_successful }
end
context "for Activity" do
it_behaves_like "a commentable controller", :activity, :activity_id
end
end

View File

@@ -0,0 +1,19 @@
# frozen_string_literal: true
FactoryBot.define do
factory :activity do
association :owner, factory: :member
sequence(:name) { |n| "Test Activity #{n}" }
description { "This is a test activity." }
category { "General" } # Example category
due_date { Time.zone.today + 1.week }
# Optional associations, uncomment and adjust if Activity model has these
# association :garden, factory: :garden
# association :planting, factory: :planting
trait :finished do
finished { true }
end
end
end

View File

@@ -2,9 +2,30 @@
FactoryBot.define do
factory :comment do
post
author
association :author, factory: :member # Explicitly use :member factory for author
sequence(:body) { |n| "OMG LOL #{n}" }
# because our commenters are more polite than YouTube's
# Default to associating with a post if no specific commentable is provided
association :commentable, factory: :post
trait :for_post do
association :commentable, factory: :post
end
trait :for_photo do
association :commentable, factory: :photo
end
trait :for_planting do
association :commentable, factory: :planting
end
trait :for_harvest do
association :commentable, factory: :harvest
end
trait :for_activity do
association :commentable, factory: :activity
end
end
end

17
spec/factories/members.rb Normal file
View File

@@ -0,0 +1,17 @@
# frozen_string_literal: true
FactoryBot.define do
factory :member do
sequence(:login_name) { |n| "member#{n}" }
sequence(:email) { |n| "member#{n}@example.com" }
password { "password123" }
password_confirmation { "password123" }
confirmed_at { Time.zone.now } # Assuming Devise confirmable is used
trait :admin do
after(:create) { |member| member.add_role(:admin) }
end
# Add other traits if needed, e.g., for specific member states or roles
end
end

View File

@@ -0,0 +1,38 @@
# frozen_string_literal: true
FactoryBot.define do
factory :planting do
association :owner, factory: :member
association :crop
association :garden
planted_at { Time.zone.today - 1.month }
description { "My awesome planting." }
quantity { 1 } # Example attribute
# Add traits if needed
trait :finished do
finished { true }
finished_at { Time.zone.today - 1.day }
end
end
end
# Assuming Crop and Garden factories are needed and might not exist
# Minimal Crop factory
FactoryBot.define do
factory :crop do
sequence(:name) { |n| "Test Crop #{n}" }
# Add other necessary attributes for Crop
# e.g., approval_status if relevant for comments
approval_status { 'approved' } # Default to approved for simplicity
end
end
# Minimal Garden factory
FactoryBot.define do
factory :garden do
association :owner, factory: :member
sequence(:name) { |n| "Test Garden #{n}" }
# Add other necessary attributes for Garden
end
end

37
spec/factories/posts.rb Normal file
View File

@@ -0,0 +1,37 @@
# frozen_string_literal: true
FactoryBot.define do
factory :post do
association :author, factory: :member
association :forum # Assuming posts belong to a forum
sequence(:subject) { |n| "Test Post Subject #{n}" }
sequence(:body) { |n| "This is the body of test post #{n}." }
# Add traits if needed, e.g., for posts with photos, crops, etc.
trait :with_photos do
transient do
photos_count { 1 }
end
after(:create) do |post, evaluator|
create_list(:photo, evaluator.photos_count, owner: post.author, post_id: post.id) # Assuming Photo has post_id or similar
end
end
trait :with_crops do
transient do
crops_count { 1 }
end
after(:create) do |post, evaluator|
create_list(:crop, evaluator.crops_count, posts: [post]) # Assuming a has_and_belongs_to_many or has_many :through
end
end
end
end
# Assuming a Forum model exists and has a factory
FactoryBot.define do
factory :forum do
sequence(:name) { |n| "Test Forum #{n}" }
# Add other attributes for Forum as needed
end
end

View File

@@ -0,0 +1,156 @@
# frozen_string_literal: true
require 'rails_helper'
RSpec.feature "Commenting on Activities", type: :feature, js: true do
let(:activity_owner) { FactoryBot.create(:member, login_name: "ActivityOwner") }
let(:commenter) { FactoryBot.create(:member, login_name: "Commenter") }
let(:other_member) { FactoryBot.create(:member, login_name: "OtherMember") }
let(:admin) { FactoryBot.create(:member, :admin, login_name: "AdminUser") }
let!(:activity) { FactoryBot.create(:activity, owner: activity_owner, name: "Gardening Day") }
def login_as(user)
visit new_member_session_path
fill_in "Login Name or Email", with: user.login_name
fill_in "Password", with: user.password
click_button "Log in"
expect(page).to have_content("Signed in successfully")
end
describe "User comments on an Activity" do
before do
login_as(commenter)
visit activity_path(activity)
end
it "allows a user to create a comment" do
expect(page).to have_content("Comments")
click_link "Add Comment"
expect(page).to have_current_path(new_activity_comment_path(activity))
expect(page).to have_content("Add comment to activity")
fill_in "comment_body", with: "Sounds like a fun activity!"
click_button "Post comment"
expect(page).to have_current_path(activity_path(activity))
expect(page).to have_content("Sounds like a fun activity!")
expect(page).to have_content(commenter.login_name)
end
end
describe "Editing comments on an Activity" do
let!(:comment_to_edit) { FactoryBot.create(:comment, commentable: activity, author: commenter, body: "Initial activity comment") }
context "as comment author" do
before do
login_as(commenter)
visit activity_path(activity)
find('.comment-body', text: "Initial activity comment").ancestor('.comment').find_button('Actions').click
click_link "Edit"
end
it "allows the author to edit their comment" do
expect(page).to have_current_path(edit_comment_path(comment_to_edit))
fill_in "comment_body", with: "Updated activity comment."
click_button "Post comment"
expect(page).to have_current_path(activity_path(activity))
expect(page).to have_content("Updated activity comment.")
expect(page).not_to have_content("Initial activity comment")
end
end
context "as admin" do
before do
login_as(admin)
visit activity_path(activity)
find('.comment-body', text: "Initial activity comment").ancestor('.comment').find_button('Actions').click
click_link "Edit"
end
it "allows admin to edit any comment" do
fill_in "comment_body", with: "Admin edited this activity comment."
click_button "Post comment"
expect(page).to have_content("Admin edited this activity comment.")
end
end
context "as unauthorized user" do
before do
login_as(other_member)
visit activity_path(activity)
end
it "does not show edit link for other's comment" do
comment_element = find('.comment-body', text: "Initial activity comment").ancestor('.comment')
expect(comment_element).not_to have_link("Edit")
expect(comment_element).not_to have_button("Actions")
end
end
end
describe "Deleting comments on an Activity" do
let!(:comment_to_delete) { FactoryBot.create(:comment, commentable: activity, author: commenter, body: "Delete this activity comment") }
context "as comment author" do
before do
login_as(commenter)
visit activity_path(activity)
find('.comment-body', text: "Delete this activity comment").ancestor('.comment').find_button('Actions').click
accept_alert { click_link "Delete" }
end
it "allows the author to delete their comment" do
expect(page).not_to have_content("Delete this activity comment")
expect(page).to have_content("Comment was successfully destroyed.")
end
end
context "as activity owner" do
before do
login_as(activity_owner)
visit activity_path(activity)
find('.comment-body', text: "Delete this activity comment").ancestor('.comment').find_button('Actions').click
accept_alert { click_link "Delete" }
end
it "allows the activity owner to delete any comment on their activity" do
expect(page).not_to have_content("Delete this activity comment")
expect(page).to have_content("Comment was successfully destroyed.")
end
end
context "as admin" do
before do
login_as(admin)
visit activity_path(activity)
find('.comment-body', text: "Delete this activity comment").ancestor('.comment').find_button('Actions').click
accept_alert { click_link "Delete" }
end
it "allows admin to delete any comment" do
expect(page).not_to have_content("Delete this activity comment")
expect(page).to have_content("Comment was successfully destroyed.")
end
end
context "as unauthorized user" do
let!(:another_comment) { FactoryBot.create(:comment, commentable: activity, author: activity_owner, body: "Activity owner's comment") }
before do
login_as(other_member)
visit activity_path(activity)
end
it "does not show delete link for other's comment" do
comment_element = find('.comment-body', text: "Activity owner's comment").ancestor('.comment')
expect(comment_element).not_to have_link("Delete")
comment_element_2 = find('.comment-body', text: "Delete this activity comment").ancestor('.comment')
expect(comment_element_2).not_to have_link("Delete")
end
end
end
end

View File

@@ -1,38 +0,0 @@
# frozen_string_literal: true
require 'rails_helper'
describe 'Commenting on a post' do
include_context 'signed in member'
let(:member) { create(:member) }
let(:post) { create(:post, author: member) }
before { visit new_comment_path post_id: post.id }
include_examples 'is accessible'
it "creating a comment" do
fill_in "comment_body", with: "This is a sample test for comment"
click_button "Post comment"
expect(page).to have_content "comment was successfully created."
expect(page).to have_content "Posted by"
page.percy_snapshot(page, name: 'Posting a comment')
end
context "editing a comment" do
let(:existing_comment) { create(:comment, post:, author: member) }
before do
visit edit_comment_path existing_comment
end
include_examples 'is accessible'
it "saving edit" do
fill_in "comment_body", with: "Testing edit for comment"
click_button "Post comment"
expect(page).to have_content "comment was successfully updated."
expect(page).to have_content "edited at"
end
end
end

View File

@@ -0,0 +1,160 @@
# frozen_string_literal: true
require 'rails_helper'
RSpec.feature "Commenting on Harvests", type: :feature, js: true do
let(:harvest_owner) { FactoryBot.create(:member, login_name: "HarvestOwner") }
let(:commenter) { FactoryBot.create(:member, login_name: "Commenter") }
let(:other_member) { FactoryBot.create(:member, login_name: "OtherMember") }
let(:admin) { FactoryBot.create(:member, :admin, login_name: "AdminUser") }
# Ensure crop, planting, and garden are created for the harvest
let(:crop) { FactoryBot.create(:crop) }
let(:garden) { FactoryBot.create(:garden, owner: harvest_owner) } # Harvest owner also owns garden for simplicity
let(:planting) { FactoryBot.create(:planting, owner: harvest_owner, crop: crop, garden: garden) }
let!(:harvest) { FactoryBot.create(:harvest, owner: harvest_owner, planting: planting, description: "My test harvest") }
def login_as(user)
visit new_member_session_path
fill_in "Login Name or Email", with: user.login_name
fill_in "Password", with: user.password
click_button "Log in"
expect(page).to have_content("Signed in successfully")
end
describe "User comments on a Harvest" do
before do
login_as(commenter)
visit harvest_path(harvest)
end
it "allows a user to create a comment" do
expect(page).to have_content("Comments")
click_link "Add Comment"
expect(page).to have_current_path(new_harvest_comment_path(harvest))
expect(page).to have_content("Add comment to harvest")
fill_in "comment_body", with: "This harvest looks bountiful!"
click_button "Post comment"
expect(page).to have_current_path(harvest_path(harvest))
expect(page).to have_content("This harvest looks bountiful!")
expect(page).to have_content(commenter.login_name)
end
end
describe "Editing comments on a Harvest" do
let!(:comment_to_edit) { FactoryBot.create(:comment, commentable: harvest, author: commenter, body: "Initial harvest comment") }
context "as comment author" do
before do
login_as(commenter)
visit harvest_path(harvest)
find('.comment-body', text: "Initial harvest comment").ancestor('.comment').find_button('Actions').click
click_link "Edit"
end
it "allows the author to edit their comment" do
expect(page).to have_current_path(edit_comment_path(comment_to_edit))
fill_in "comment_body", with: "Updated harvest comment."
click_button "Post comment"
expect(page).to have_current_path(harvest_path(harvest))
expect(page).to have_content("Updated harvest comment.")
expect(page).not_to have_content("Initial harvest comment")
end
end
context "as admin" do
before do
login_as(admin)
visit harvest_path(harvest)
find('.comment-body', text: "Initial harvest comment").ancestor('.comment').find_button('Actions').click
click_link "Edit"
end
it "allows admin to edit any comment" do
fill_in "comment_body", with: "Admin edited this harvest comment."
click_button "Post comment"
expect(page).to have_content("Admin edited this harvest comment.")
end
end
context "as unauthorized user" do
before do
login_as(other_member)
visit harvest_path(harvest)
end
it "does not show edit link for other's comment" do
comment_element = find('.comment-body', text: "Initial harvest comment").ancestor('.comment')
expect(comment_element).not_to have_link("Edit")
expect(comment_element).not_to have_button("Actions")
end
end
end
describe "Deleting comments on a Harvest" do
let!(:comment_to_delete) { FactoryBot.create(:comment, commentable: harvest, author: commenter, body: "Delete this harvest comment") }
context "as comment author" do
before do
login_as(commenter)
visit harvest_path(harvest)
find('.comment-body', text: "Delete this harvest comment").ancestor('.comment').find_button('Actions').click
accept_alert { click_link "Delete" }
end
it "allows the author to delete their comment" do
expect(page).not_to have_content("Delete this harvest comment")
expect(page).to have_content("Comment was successfully destroyed.")
end
end
context "as harvest owner" do
before do
login_as(harvest_owner)
visit harvest_path(harvest)
find('.comment-body', text: "Delete this harvest comment").ancestor('.comment').find_button('Actions').click
accept_alert { click_link "Delete" }
end
it "allows the harvest owner to delete any comment on their harvest" do
expect(page).not_to have_content("Delete this harvest comment")
expect(page).to have_content("Comment was successfully destroyed.")
end
end
context "as admin" do
before do
login_as(admin)
visit harvest_path(harvest)
find('.comment-body', text: "Delete this harvest comment").ancestor('.comment').find_button('Actions').click
accept_alert { click_link "Delete" }
end
it "allows admin to delete any comment" do
expect(page).not_to have_content("Delete this harvest comment")
expect(page).to have_content("Comment was successfully destroyed.")
end
end
context "as unauthorized user" do
let!(:another_comment) { FactoryBot.create(:comment, commentable: harvest, author: harvest_owner, body: "Harvest owner's comment") }
before do
login_as(other_member)
visit harvest_path(harvest)
end
it "does not show delete link for other's comment" do
comment_element = find('.comment-body', text: "Harvest owner's comment").ancestor('.comment')
expect(comment_element).not_to have_link("Delete")
comment_element_2 = find('.comment-body', text: "Delete this harvest comment").ancestor('.comment')
expect(comment_element_2).not_to have_link("Delete")
end
end
end
end

View File

@@ -0,0 +1,158 @@
# frozen_string_literal: true
require 'rails_helper'
RSpec.feature "Commenting on Photos", type: :feature, js: true do
let(:photo_owner) { FactoryBot.create(:member, login_name: "PhotoOwner") }
let(:commenter) { FactoryBot.create(:member, login_name: "Commenter") }
let(:other_member) { FactoryBot.create(:member, login_name: "OtherMember") }
let(:admin) { FactoryBot.create(:member, :admin, login_name: "AdminUser") }
let!(:photo) { FactoryBot.create(:photo, owner: photo_owner, title: "Beautiful Sunset") }
def login_as(user)
visit new_member_session_path
fill_in "Login Name or Email", with: user.login_name
fill_in "Password", with: user.password
click_button "Log in"
expect(page).to have_content("Signed in successfully")
end
describe "User comments on a Photo" do
before do
login_as(commenter)
visit photo_path(photo)
end
it "allows a user to create a comment" do
expect(page).to have_content("Comments")
click_link "Add Comment" # From the _comments partial
expect(page).to have_current_path(new_photo_comment_path(photo))
expect(page).to have_content("Add comment to photo")
fill_in "comment_body", with: "What a stunning photo!"
click_button "Post comment"
expect(page).to have_current_path(photo_path(photo))
expect(page).to have_content("What a stunning photo!")
expect(page).to have_content(commenter.login_name)
end
end
describe "Editing comments on a Photo" do
let!(:comment_to_edit) { FactoryBot.create(:comment, commentable: photo, author: commenter, body: "Initial comment body") }
context "as comment author" do
before do
login_as(commenter)
visit photo_path(photo)
# Find the comment section and then the edit button within it.
# This assumes the comment body is unique enough or we can find by specific data-testid attributes if added.
find('.comment-body', text: "Initial comment body").ancestor('.comment').find_button('Actions').click
click_link "Edit"
end
it "allows the author to edit their comment" do
expect(page).to have_current_path(edit_comment_path(comment_to_edit))
fill_in "comment_body", with: "Updated comment body here."
click_button "Post comment"
expect(page).to have_current_path(photo_path(photo))
expect(page).to have_content("Updated comment body here.")
expect(page).not_to have_content("Initial comment body")
end
end
context "as admin" do
before do
login_as(admin)
visit photo_path(photo)
find('.comment-body', text: "Initial comment body").ancestor('.comment').find_button('Actions').click
click_link "Edit"
end
it "allows admin to edit any comment" do
fill_in "comment_body", with: "Admin edited this comment."
click_button "Post comment"
expect(page).to have_content("Admin edited this comment.")
end
end
context "as unauthorized user" do
before do
login_as(other_member)
visit photo_path(photo)
end
it "does not show edit link for other's comment" do
# Check within the specific comment's scope
comment_element = find('.comment-body', text: "Initial comment body").ancestor('.comment')
expect(comment_element).not_to have_link("Edit")
expect(comment_element).not_to have_button("Actions") # Or check that Actions doesn't show Edit
end
end
end
describe "Deleting comments on a Photo" do
let!(:comment_to_delete) { FactoryBot.create(:comment, commentable: photo, author: commenter, body: "This will be deleted") }
context "as comment author" do
before do
login_as(commenter)
visit photo_path(photo)
find('.comment-body', text: "This will be deleted").ancestor('.comment').find_button('Actions').click
accept_alert { click_link "Delete" }
end
it "allows the author to delete their comment" do
expect(page).not_to have_content("This will be deleted")
expect(page).to have_content("Comment was successfully destroyed.") # Assuming flash message
end
end
context "as photo owner" do
before do
login_as(photo_owner)
visit photo_path(photo)
find('.comment-body', text: "This will be deleted").ancestor('.comment').find_button('Actions').click
accept_alert { click_link "Delete" }
end
it "allows the photo owner to delete any comment on their photo" do
expect(page).not_to have_content("This will be deleted")
expect(page).to have_content("Comment was successfully destroyed.")
end
end
context "as admin" do
before do
login_as(admin)
visit photo_path(photo)
find('.comment-body', text: "This will be deleted").ancestor('.comment').find_button('Actions').click
accept_alert { click_link "Delete" }
end
it "allows admin to delete any comment" do
expect(page).not_to have_content("This will be deleted")
expect(page).to have_content("Comment was successfully destroyed.")
end
end
context "as unauthorized user" do
let!(:another_comment) { FactoryBot.create(:comment, commentable: photo, author: photo_owner, body: "Photo owner's comment") }
before do
login_as(other_member) # other_member is not admin, not photo_owner, not author of `another_comment`
visit photo_path(photo)
end
it "does not show delete link for other's comment" do
comment_element = find('.comment-body', text: "Photo owner's comment").ancestor('.comment')
expect(comment_element).not_to have_link("Delete")
# Also check the original comment_to_delete by commenter
comment_element_2 = find('.comment-body', text: "This will be deleted").ancestor('.comment')
expect(comment_element_2).not_to have_link("Delete")
end
end
end
end

View File

@@ -0,0 +1,158 @@
# frozen_string_literal: true
require 'rails_helper'
RSpec.feature "Commenting on Plantings", type: :feature, js: true do
let(:planting_owner) { FactoryBot.create(:member, login_name: "PlantingOwner") }
let(:commenter) { FactoryBot.create(:member, login_name: "Commenter") }
let(:other_member) { FactoryBot.create(:member, login_name: "OtherMember") }
let(:admin) { FactoryBot.create(:member, :admin, login_name: "AdminUser") }
# Ensure crop and garden are created for the planting
let(:crop) { FactoryBot.create(:crop) }
let(:garden) { FactoryBot.create(:garden, owner: planting_owner) }
let!(:planting) { FactoryBot.create(:planting, owner: planting_owner, crop: crop, garden: garden, description: "My test planting") }
def login_as(user)
visit new_member_session_path
fill_in "Login Name or Email", with: user.login_name
fill_in "Password", with: user.password
click_button "Log in"
expect(page).to have_content("Signed in successfully")
end
describe "User comments on a Planting" do
before do
login_as(commenter)
visit planting_path(planting)
end
it "allows a user to create a comment" do
expect(page).to have_content("Comments")
click_link "Add Comment"
expect(page).to have_current_path(new_planting_comment_path(planting))
expect(page).to have_content("Add comment to planting")
fill_in "comment_body", with: "This planting looks great!"
click_button "Post comment"
expect(page).to have_current_path(planting_path(planting))
expect(page).to have_content("This planting looks great!")
expect(page).to have_content(commenter.login_name)
end
end
describe "Editing comments on a Planting" do
let!(:comment_to_edit) { FactoryBot.create(:comment, commentable: planting, author: commenter, body: "Initial planting comment") }
context "as comment author" do
before do
login_as(commenter)
visit planting_path(planting)
find('.comment-body', text: "Initial planting comment").ancestor('.comment').find_button('Actions').click
click_link "Edit"
end
it "allows the author to edit their comment" do
expect(page).to have_current_path(edit_comment_path(comment_to_edit))
fill_in "comment_body", with: "Updated planting comment."
click_button "Post comment"
expect(page).to have_current_path(planting_path(planting))
expect(page).to have_content("Updated planting comment.")
expect(page).not_to have_content("Initial planting comment")
end
end
context "as admin" do
before do
login_as(admin)
visit planting_path(planting)
find('.comment-body', text: "Initial planting comment").ancestor('.comment').find_button('Actions').click
click_link "Edit"
end
it "allows admin to edit any comment" do
fill_in "comment_body", with: "Admin edited this planting comment."
click_button "Post comment"
expect(page).to have_content("Admin edited this planting comment.")
end
end
context "as unauthorized user" do
before do
login_as(other_member)
visit planting_path(planting)
end
it "does not show edit link for other's comment" do
comment_element = find('.comment-body', text: "Initial planting comment").ancestor('.comment')
expect(comment_element).not_to have_link("Edit")
expect(comment_element).not_to have_button("Actions")
end
end
end
describe "Deleting comments on a Planting" do
let!(:comment_to_delete) { FactoryBot.create(:comment, commentable: planting, author: commenter, body: "Delete this planting comment") }
context "as comment author" do
before do
login_as(commenter)
visit planting_path(planting)
find('.comment-body', text: "Delete this planting comment").ancestor('.comment').find_button('Actions').click
accept_alert { click_link "Delete" }
end
it "allows the author to delete their comment" do
expect(page).not_to have_content("Delete this planting comment")
expect(page).to have_content("Comment was successfully destroyed.")
end
end
context "as planting owner" do
before do
login_as(planting_owner)
visit planting_path(planting)
find('.comment-body', text: "Delete this planting comment").ancestor('.comment').find_button('Actions').click
accept_alert { click_link "Delete" }
end
it "allows the planting owner to delete any comment on their planting" do
expect(page).not_to have_content("Delete this planting comment")
expect(page).to have_content("Comment was successfully destroyed.")
end
end
context "as admin" do
before do
login_as(admin)
visit planting_path(planting)
find('.comment-body', text: "Delete this planting comment").ancestor('.comment').find_button('Actions').click
accept_alert { click_link "Delete" }
end
it "allows admin to delete any comment" do
expect(page).not_to have_content("Delete this planting comment")
expect(page).to have_content("Comment was successfully destroyed.")
end
end
context "as unauthorized user" do
let!(:another_comment) { FactoryBot.create(:comment, commentable: planting, author: planting_owner, body: "Planting owner's comment") }
before do
login_as(other_member)
visit planting_path(planting)
end
it "does not show delete link for other's comment" do
comment_element = find('.comment-body', text: "Planting owner's comment").ancestor('.comment')
expect(comment_element).not_to have_link("Delete")
comment_element_2 = find('.comment-body', text: "Delete this planting comment").ancestor('.comment')
expect(comment_element_2).not_to have_link("Delete")
end
end
end
end

View File

@@ -0,0 +1,176 @@
# frozen_string_literal: true
require 'rails_helper'
RSpec.feature "Commenting on Posts", type: :feature, js: true do
# Use existing 'signed in member' shared context if it provides Capybara login helper
# Otherwise, define one locally or ensure one is available.
# For consistency with other new specs, defining a local login_as helper.
let(:post_author) { FactoryBot.create(:member, login_name: "PostAuthor") }
let(:commenter) { FactoryBot.create(:member, login_name: "Commenter") }
let(:other_member) { FactoryBot.create(:member, login_name: "OtherMember") }
let(:admin) { FactoryBot.create(:member, :admin, login_name: "AdminUser") }
# Ensure a forum is created for the post if your Post factory/model requires it
let!(:forum) { FactoryBot.create(:forum) }
let!(:post) { FactoryBot.create(:post, author: post_author, forum: forum, subject: "My Test Post") }
def login_as(user)
visit new_member_session_path
fill_in "Login Name or Email", with: user.login_name
fill_in "Password", with: user.password
click_button "Log in"
expect(page).to have_content("Signed in successfully")
end
# Include shared examples for accessibility if they exist and are relevant
# For now, focusing on the commenting CRUD operations.
# The original spec had: include_examples 'is accessible'
# If this shared example exists and is desired, it can be added to relevant `before` blocks.
describe "User comments on a Post" do
before do
login_as(commenter)
visit post_path(post)
end
it "allows a user to create a comment" do
expect(page).to have_content("Comments") # From the _comments partial
# The "Add Comment" link is now within the _comments partial
# If the _comments partial is set up to show the form directly or link to new, this will work.
# Assuming it has a link:
click_link "Add Comment"
expect(page).to have_current_path(new_post_comment_path(post))
expect(page).to have_content("Add comment to post")
fill_in "comment_body", with: "This is a great post!"
click_button "Post comment"
expect(page).to have_current_path(post_path(post)) # Should redirect back to the post
expect(page).to have_content("This is a great post!")
expect(page).to have_content(commenter.login_name)
# Check for flash message if your controller sets one, e.g.:
# expect(page).to have_content("Comment was successfully created.")
end
end
describe "Editing comments on a Post" do
let!(:comment_to_edit) { FactoryBot.create(:comment, commentable: post, author: commenter, body: "Initial post comment") }
context "as comment author" do
before do
login_as(commenter)
visit post_path(post)
find('.comment-body', text: "Initial post comment").ancestor('.comment').find_button('Actions').click
click_link "Edit"
end
it "allows the author to edit their comment" do
expect(page).to have_current_path(edit_comment_path(comment_to_edit))
fill_in "comment_body", with: "Updated post comment."
click_button "Post comment"
expect(page).to have_current_path(post_path(post))
expect(page).to have_content("Updated post comment.")
expect(page).not_to have_content("Initial post comment")
# Check for flash message if your controller sets one, e.g.:
# expect(page).to have_content("Comment was successfully updated.")
end
end
context "as admin" do
before do
login_as(admin)
visit post_path(post)
find('.comment-body', text: "Initial post comment").ancestor('.comment').find_button('Actions').click
click_link "Edit"
end
it "allows admin to edit any comment" do
fill_in "comment_body", with: "Admin edited this post comment."
click_button "Post comment"
expect(page).to have_content("Admin edited this post comment.")
end
end
context "as unauthorized user" do
before do
login_as(other_member)
visit post_path(post)
end
it "does not show edit link for other's comment" do
comment_element = find('.comment-body', text: "Initial post comment").ancestor('.comment')
expect(comment_element).not_to have_link("Edit")
expect(comment_element).not_to have_button("Actions")
end
end
end
describe "Deleting comments on a Post" do
let!(:comment_to_delete) { FactoryBot.create(:comment, commentable: post, author: commenter, body: "Delete this post comment") }
context "as comment author" do
before do
login_as(commenter)
visit post_path(post)
find('.comment-body', text: "Delete this post comment").ancestor('.comment').find_button('Actions').click
accept_alert { click_link "Delete" }
end
it "allows the author to delete their comment" do
expect(page).not_to have_content("Delete this post comment")
expect(page).to have_content("Comment was successfully destroyed.") # Assuming flash message
end
end
context "as post author (owner of commentable)" do
before do
# Ensure commenter is not the post_author for this specific test
expect(commenter).not_to eq(post_author)
login_as(post_author)
visit post_path(post)
find('.comment-body', text: "Delete this post comment").ancestor('.comment').find_button('Actions').click
accept_alert { click_link "Delete" }
end
it "allows the post author to delete any comment on their post" do
expect(page).not_to have_content("Delete this post comment")
expect(page).to have_content("Comment was successfully destroyed.")
end
end
context "as admin" do
before do
login_as(admin)
visit post_path(post)
find('.comment-body', text: "Delete this post comment").ancestor('.comment').find_button('Actions').click
accept_alert { click_link "Delete" }
end
it "allows admin to delete any comment" do
expect(page).not_to have_content("Delete this post comment")
expect(page).to have_content("Comment was successfully destroyed.")
end
end
context "as unauthorized user" do
# Create a comment by the post_author to test against
let!(:another_comment) { FactoryBot.create(:comment, commentable: post, author: post_author, body: "Post author's comment") }
before do
login_as(other_member) # other_member is not admin, not post_author, not author of `another_comment`
visit post_path(post)
end
it "does not show delete link for other's comment" do
comment_element = find('.comment-body', text: "Post author's comment").ancestor('.comment')
expect(comment_element).not_to have_link("Delete")
# Also check the original comment_to_delete by commenter
comment_element_2 = find('.comment-body', text: "Delete this post comment").ancestor('.comment')
expect(comment_element_2).not_to have_link("Delete")
end
end
end
end

View File

@@ -3,53 +3,152 @@
require 'rails_helper'
describe Comment do
context "basic" do
let(:comment) { FactoryBot.create(:comment) }
context "associations" do
let(:member) { FactoryBot.create(:member) } # Common author
it "belongs to a post" do
comment.post.should be_an_instance_of Post
it "belongs to a commentable (Post)" do
post = FactoryBot.create(:post, author: member)
comment = FactoryBot.create(:comment, commentable: post, author: member)
comment.commentable.should be_an_instance_of Post
end
it "belongs to a commentable (Photo)" do
photo = FactoryBot.create(:photo, owner: member)
comment = FactoryBot.create(:comment, commentable: photo, author: member)
comment.commentable.should be_an_instance_of Photo
end
it "belongs to a commentable (Planting)" do
planting = FactoryBot.create(:planting, owner: member)
comment = FactoryBot.create(:comment, commentable: planting, author: member)
comment.commentable.should be_an_instance_of Planting
end
it "belongs to a commentable (Harvest)" do
harvest = FactoryBot.create(:harvest, owner: member)
comment = FactoryBot.create(:comment, commentable: harvest, author: member)
comment.commentable.should be_an_instance_of Harvest
end
it "belongs to a commentable (Activity)" do
activity = FactoryBot.create(:activity, owner: member)
comment = FactoryBot.create(:comment, commentable: activity, author: member)
comment.commentable.should be_an_instance_of Activity
end
it "belongs to an author" do
comment = FactoryBot.create(:comment, author: member) # Default commentable is Post
comment.author.should be_an_instance_of Member
end
end
context "notifications" do
RSpec.shared_examples "comment notifications" do |commentable_type, commentable_factory_name|
let(:commentable_owner) { FactoryBot.create(:member) }
let(:comment_author) { FactoryBot.create(:member) }
let!(:commentable) do
# For :post, the owner is :author. For others, it's :owner.
if commentable_factory_name == :post
FactoryBot.create(commentable_factory_name, author: commentable_owner)
else
FactoryBot.create(commentable_factory_name, owner: commentable_owner)
end
end
it "sends a notification when a comment is posted" do
expect do
FactoryBot.create(:comment)
FactoryBot.create(:comment, commentable: commentable, author: comment_author)
end.to change(Notification, :count).by(1)
end
it "sets the notification fields" do
@c = FactoryBot.create(:comment)
@n = Notification.first
@n.sender.should eq @c.author
@n.recipient.should eq @c.post.author
@n.subject.should include 'commented on'
@n.body.should eq @c.body
@n.post.should eq @c.post
it "sets the notification fields correctly" do
comment = FactoryBot.create(:comment, commentable: commentable, author: comment_author)
notification = Notification.last # More robust than Notification.first
notification.sender.should eq comment.author
notification.recipient.should eq commentable_owner
notification.subject.should include "commented on your #{commentable_type.downcase}"
notification.body.should eq comment.body
notification.commentable_id.should eq commentable.id
notification.commentable_type.should eq commentable_type
end
it "doesn't send notifications to yourself" do
@m = FactoryBot.create(:member)
@p = FactoryBot.create(:post, author: @m)
it "doesn't send notifications to yourself (when comment author is commentable owner)" do
expect do
FactoryBot.create(:comment, post: @p, author: @m)
FactoryBot.create(:comment, commentable: commentable, author: commentable_owner)
end.not_to change(Notification, :count)
end
end
context "notifications for Post" do
include_examples "comment notifications", "Post", :post
end
context "notifications for Photo" do
include_examples "comment notifications", "Photo", :photo
end
context "notifications for Planting" do
include_examples "comment notifications", "Planting", :planting
end
context "notifications for Harvest" do
include_examples "comment notifications", "Harvest", :harvest
end
context "notifications for Activity" do
include_examples "comment notifications", "Activity", :activity
end
RSpec.shared_examples "comment to_s method" do |commentable_type, commentable_factory_name|
let(:commentable_owner) { FactoryBot.create(:member) }
let(:comment_author) { FactoryBot.create(:member, login_name: "CommenterUser") }
let!(:commentable) do
# For :post, the owner is :author. For others, it's :owner.
obj = if commentable_factory_name == :post
FactoryBot.create(commentable_factory_name, author: commentable_owner)
else
FactoryBot.create(commentable_factory_name, owner: commentable_owner)
end
# Ensure commentable has a consistent ID for the test if possible, or just use its class name
obj
end
let(:comment) { FactoryBot.create(:comment, commentable: commentable, author: comment_author) }
it "returns a descriptive string" do
expected_string = "#{comment_author.login_name} commented on #{commentable_type.downcase} ##{commentable.id}"
comment.to_s.should eq expected_string
end
end
context "to_s method for Post" do
include_examples "comment to_s method", "Post", :post
end
context "to_s method for Photo" do
include_examples "comment to_s method", "Photo", :photo
end
context "to_s method for Planting" do
include_examples "comment to_s method", "Planting", :planting
end
context "to_s method for Harvest" do
include_examples "comment to_s method", "Harvest", :harvest
end
context "to_s method for Activity" do
include_examples "comment to_s method", "Activity", :activity
end
context "ordering" do
before do
@m = FactoryBot.create(:member)
# Ensure the commentable for ordering test is a Post, as it was originally
@p = FactoryBot.create(:post, author: @m)
@c1 = FactoryBot.create(:comment, post: @p, author: @m)
@c2 = FactoryBot.create(:comment, post: @p, author: @m)
@c1 = FactoryBot.create(:comment, commentable: @p, author: @m)
@c2 = FactoryBot.create(:comment, commentable: @p, author: @m)
end
it 'has a scope for ASC order for displaying on post page' do
it 'has a scope for ASC order for displaying on commentable page' do # Renamed for clarity
described_class.post_order.should eq [@c1, @c2]
end
end

View File

@@ -2,6 +2,11 @@
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require 'simplecov'
# output coverage locally AND send it to coveralls
SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter.new([SimpleCov::Formatter::HTMLFormatter])
require 'spec_helper'
require File.expand_path('../config/environment', __dir__)
require 'rspec/rails'
@@ -15,13 +20,13 @@ require 'capybara-screenshot/rspec'
require 'axe-capybara'
require 'axe-rspec'
# TODO: We may want to trial options.add_argument('--disable-dev-shm-usage') ### optional
# Required for running in the dev container
Capybara.register_driver :selenium_chrome_customised_headless do |app|
options = Selenium::WebDriver::Options.chrome
options.add_argument("--headless")
options.add_argument("--no-sandbox")
options.add_argument("--window-size=1920,1080")
options.add_argument("--disable-dev-shm-usage")
# driver = Selenium::WebDriver.for :chrome, options: options
@@ -120,8 +125,8 @@ RSpec.configure do |config|
# Prevent Poltergeist from fetching external URLs during feature tests
config.before(:each, :js) do
# TODO: Why are we setting this page size then straight afterwards, maximising?
width = 1920
height = 1080
width = 1280
height = 1280
Capybara.current_session.driver.browser.manage.window.resize_to(width, height)
if page.driver.browser.respond_to?(:url_blacklist)
@@ -132,9 +137,6 @@ RSpec.configure do |config|
]
end
# Historically, we wanted to .maximize; but this actually undoes the resize_to step above
# with chrome headless
# page.driver.browser.manage.window.maximize if page.driver.browser.respond_to?(:manage)
# puts "Maximized window size: #{page.driver.browser.manage.window.size}"
page.driver.browser.manage.window.maximize if page.driver.browser.respond_to?(:manage)
end
end

View File

@@ -16,8 +16,8 @@
# users commonly want.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
require 'simplecov'
require 'percy/capybara'
require 'rspec/rebound'
require 'vcr'
VCR.configure do |c|
@@ -27,6 +27,8 @@ VCR.configure do |c|
c.configure_rspec_metadata!
end
SimpleCov.start
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
@@ -124,20 +126,4 @@ RSpec.configure do |config|
# Remember which tests failed, so you can run rspec with the `--only-failures` flag.
config.example_status_persistence_file_path = "tmp/examples.txt"
# show retry status in spec process
config.verbose_retry = true
# show exception that triggers a retry if verbose_retry is set to true
config.display_try_failure_messages = true
# run retry only on features
config.around :each, :js do |ex|
ex.run_with_retry retry: 3
end
# callback to be run between retries
config.retry_callback = proc do |ex|
# run some additional clean up task - can be filtered by example metadata
Capybara.reset! if ex.metadata[:js]
end
end

View File

@@ -1,33 +0,0 @@
# frozen_string_literal: true
require 'rails_helper'
require 'rake'
describe 'openfarm:delete_pictures' do
before(:all) do
Rails.application.load_tasks
end
# We need to do this because Rake tasks normally output to STDOUT, but we
# don't want to clutter up the test output.
before(:each) do
$stdout = StringIO.new
end
after(:each) do
$stdout = STDOUT
end
it 'deletes pictures with source OpenFarm' do
create(:photo, source: 'OpenFarm')
create(:photo, source: 'flickr')
expect(Photo.where(source: 'OpenFarm').count).to eq(1)
expect(Photo.where(source: 'flickr').count).to eq(1)
Rake::Task['openfarm:delete_pictures'].invoke
expect(Photo.where(source: 'OpenFarm').count).to eq(0)
expect(Photo.where(source: 'flickr').count).to eq(1)
end
end