Я новичок в Ruby on Rails и в настоящее время зарегистрирован на курсе Bloc.io, который поручил мне создавать тесты RSpec, которые возвращают, было ли сообщение предоставлено конкретным пользователем.RSpec Тестирование для возврата Избранные сообщения
Вот мой текущий RSpec файл:
require 'rails_helper'
describe User do
include TestFactories
describe "#favorited(post)" do
before do
@post = associated_post
@user = authenticated_user
end
it "returns `nil` if the user has not favorited the post" do
expect(@user.favorited(@post)).to be_nil
end
it "returns the appropriate favorite if it exists" do
favorite = Favorite.new
expect(@user.favorite).to eq(favorited(@post))
end
it "returns `nil` if the user has favorited another post" do
end
end
end
Я был успешным в прохождении первого теста (it "returns 'nil' if the user has not favorited the post"
), но я озадачен о том, как получить вторые и третьи тесты, чтобы пройти.
Я думаю, что я в настоящее время приступил ко второму испытанию (it "returns 'nil' if the user has not favorited the post"
) является правильным и считаю, мне нужно поставить хэш Favorite.new
, что бы назначить его на должность и пользователь, но не уверен, что будет необходимо передать . в
Вот мой включен TestFactories
файл только упаковывают, который помогает:
module TestFactories
def associated_post(options={})
post_options = {
title: 'Post title',
body: 'Post bodies must be pretty long.',
topic: Topic.create(name: 'Topic name'),
user: authenticated_user
}.merge(options)
Post.create(post_options)
end
def authenticated_user(options={})
user_options = {email: 'email#{rand}@fake.com', password: 'password'}.merge(options)
user = User.new(user_options)
user.skip_confirmation!
user.save
user
end
end
, а также мой #favorited(post)
метод:
def favorited(post)
favorites.where(post_id: post.id).first
end
EDIT:
Вот Favorite Модель:
class Favorite < ActiveRecord::Base
belongs_to :post
belongs_to :user
end
второй EDIT:
я смог немного изменить мой код для моего второго теста:
it "returns the appropriate favorite if it exists" do
favorite = Favorite.create(user: @user, post: @post)
expect(@user.favorited(@post)).to eq(favorite)
end
Теперь я получаю следующие сбои/ошибки:
Failures:
1) User#favorited(post) returns the appropriate favorite if it exists
Failure/Error: expect(@user.favorited(@post)).to eq(favorite)
expected: #<Favorite id: 1, post_id: 1, user_id: nil, created_at: "2015-04-26 04:16:37", updated_at: "2015-04-26 04:16:37">
got: nil
(compared using ==)
# ./spec/models/user_spec.rb:20:in `block (3 levels) in <top (required)>'
Finished in 0.53769 seconds (files took 3.21 seconds to load)
3 examples, 1 failure, 1 pending
Failed examples:
rspec ./spec/models/user_spec.rb:18 # User#favorited(post) returns the appropriate favorite if it exists
Похоже, что у теста есть проблема с поиском идентификатора для указанного пользователя. Как я могу найти и назначить идентификатор указанного пользователя?
Любые идеи, чтобы привести меня в правильном направлении?
Спасибо!
Пожалуйста, укажите ваш код для модели 'Favorite'. Особенно его ассоциации. – Drenmi
Благодарим вас за ответ @Drenmi. Я добавил Любимую модель, показывающую ее правильную связь. – brianstone