我查看了所有相关帖子,但无法弄清楚如何让我的测试通过...我一直收到一个错误,说Food.count应该已经改变1但是没有。我不确定它是否与我的create方法正在建立关系的事实有关?
def create
@food = current_user.foods.build(food_params)
if @food.save
redirect_to user_path(@food.user_id)
else
render 'new'
end
end
class Food < ApplicationRecord
belongs_to :user
has_many :votes, dependent: :destroy
validates :title, :kind, :image, presence: true
mount_uploader :image, ImageUploader
def Food.random_soup
Food.all.where(kind: 'soup').shuffle
end
end
create_table "foods", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "kind"
t.string "title"
t.integer "wins"
t.integer "loses"
t.integer "user_id"
t.string "image"
t.text "recipe"
t.text "description"
end
before(:each) do
user = create(:user)
sign_in(user)
end
describe "POST create" do
context "with valid attributes" do
it "creates a new food" do
food_params = FactoryGirl.attributes_for(:food)
expect { post :create, :food => food_params }.to change(Food, :count).by(1)
end
end
end
factory :food do |f|
f.kind "soup"
f.title "Clam Chowder"
f.id 1
f.image File.open(File.join(Rails.root, '/app/assets/images/Canada.png'))
end
答案 0 :(得分:0)
如果不了解更多关于@food
对象的信息,很难回答这个问题。
有很多问题可能出错(food_params
不完整或格式错误,@food.save
返回错误等等)
当像这样的简单测试没有通过最好的事情(从过去的经验)是将一些“关键”binding.pry
扔进你的创建方法,以确切看到你运行时发生了什么你的考试。
如果您不熟悉gem pry
,我建议您阅读README,但它本质上是一种停止执行的方法,并使用像REPL这样的IRB。
def create
binding.pry
# check to see what the original count is / current_user
@food = current_user.foods.build(food_params)
binding.pry
# confirm that the relationship has been built (could be an issue with the way you are passing in params in the test and would be apparent here)
# + check the return value of @food.save
if @food.save
redirect_to user_path(@food.user_id)
else
render 'new'
end
end
使用这两个pry
您应该能够看到确切的内容(create
方法的问题或测试设置的小问题。
祝你通过测试好运
答案 1 :(得分:0)
我怀疑你的测试工作正常,而@food实际上是无效的。
如果没有关于食物模型的更多详细信息,我可以建议您尝试以下内容来确定错误:
describe "POST create" do
context "with invalid attributes" do
it "should set errors" do
food_params = FactoryGirl.attributes_for(:food)
post :create, :food => food_params
puts assigns(:food).errors.inspect
end
end
end