upto 4.3: favourite style

This commit is contained in:
Aaro Koivukangas
2023-08-16 09:54:07 +03:00
parent 9a3ae5e0eb
commit ca680d7c04
5 changed files with 90 additions and 0 deletions
+1
View File
@@ -70,6 +70,7 @@ group :test do
gem "selenium-webdriver"
gem "webdrivers"
gem "rspec-rails"
gem "factory_bot_rails"
end
+6
View File
@@ -92,6 +92,11 @@ GEM
reline (>= 0.3.1)
diff-lcs (1.5.0)
erubi (1.12.0)
factory_bot (6.2.1)
activesupport (>= 5.0.0)
factory_bot_rails (6.2.0)
factory_bot (~> 6.2.0)
railties (>= 5.0.0)
globalid (1.1.0)
activesupport (>= 5.0)
i18n (1.13.0)
@@ -242,6 +247,7 @@ DEPENDENCIES
bootsnap
capybara
debug
factory_bot_rails
importmap-rails
jbuilder
pg
+21
View File
@@ -18,4 +18,25 @@ class User < ApplicationRecord
errors.add :password, "doesn't contain uppercase letter and a number"
end
def favorite_style
# create hash with key being style name and value first 0 and then the score
styles = {}
self.ratings.each do |rating|
styles[rating.beer.style] = 0
end
self.ratings.each do |rating|
styles[rating.beer.style] += rating.score
end
# determine which style hast the most points
highest = {name: "", total: 0}
styles.each do |style|
if style[1] > highest[:total]
highest[:name] = style[0]
highest[:total] = style[1]
end
end
return highest[:name]
end
end
+24
View File
@@ -0,0 +1,24 @@
FactoryBot.define do
factory :user do
username { "Möötti" }
password { "Unsecure1" }
password_confirmation { "Unsecure1" }
end
factory :brewery do
name { "Creative" }
year { 2023 }
end
factory :beer do
name { "Something good" }
style { "Yes" }
brewery
end
factory :rating do
score { 15 }
beer
user
end
end
+38
View File
@@ -27,4 +27,42 @@ RSpec.describe User, type: :model do
expect(userMöötti).to_not be_valid
expect(userMaatti).to_not be_valid
end
describe "favourite_style" do
let(:user){ FactoryBot.create(:user) }
let(:brewery){ FactoryBot.create(:brewery) }
it "is defined method" do
expect(user).to respond_to(:favorite_style)
end
it "returns a string" do
expect(user.favorite_style).to be_a(String)
end
it "returns the most liked style" do
create_beer_with_many_ratings({user: user}, 10, 10, 20)
beer_with_favorite_style = FactoryBot.create(:beer, style: "No")
FactoryBot.create(:rating, beer: beer_with_favorite_style, score: 50, user: user)
expect(user.favorite_style).to eq "No"
end
it "also returns the most liked style" do
create_beer_with_many_ratings({user: user}, 20, 30, 20)
beer_with_favorite_style = FactoryBot.create(:beer, style: "No")
FactoryBot.create(:rating, beer: beer_with_favorite_style, score: 50, user: user)
end
end
end
def create_beer_with_rating(object, score)
beer = FactoryBot.create(:beer)
rating = FactoryBot.create(:rating, beer: beer, score: score, user: object[:user])
end
def create_beer_with_many_ratings(object, *scores)
scores.each do |score|
create_beer_with_rating(object, score)
end
end