Ruby on rails 关系控制器的Rspec失败,无法';找不到使用';id'=
我正在尝试为我的关系控制器制定规范,但#create方法失败(找不到id为的用户)。 你能告诉我怎么修理这个吗? 谢谢您的帮助,如果您有任何问题,请询问。:) 与财务主任的关系:Ruby on rails 关系控制器的Rspec失败,无法';找不到使用';id'=,ruby-on-rails,unit-testing,rspec,rspec-rails,Ruby On Rails,Unit Testing,Rspec,Rspec Rails,我正在尝试为我的关系控制器制定规范,但#create方法失败(找不到id为的用户)。 你能告诉我怎么修理这个吗? 谢谢您的帮助,如果您有任何问题,请询问。:) 与财务主任的关系: class RelationshipsController < InheritedResources::Base def create user = User.find(params[:followed_id]) current_user.follow(user) redirect_
class RelationshipsController < InheritedResources::Base
def create
user = User.find(params[:followed_id])
current_user.follow(user)
redirect_to user
end
def destroy
user = Relationship.find(params[:id]).followed
current_user.unfollow(user)
redirect_to user
end
end
失败:
RelationshipsController
#create
should require logged-in user to destroy relationship
#create
should require logged-in user to create relationship (FAILED - 1)
Failures:
1) RelationshipsController#create should require logged-in user to create relationship
Failure/Error:
expect{
Relationship.create
}.to change(Relationship, :count).by(1)
expected #count to have changed by 1, but was changed by 0
关系:
class Relationship < ActiveRecord::Base
#Associations
belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "User"
#Validations
validates :follower_id, presence: true
validates :followed_id, presence: true
end
类关系
用户:
class用户
在您的测试中-
describe RelationshipsController do
let(:relationship) { create(:relationship) }
let(:user) { create(:user) }
直到需要时才创建用户
describe RelationshipsController do
let(:relationship) { create(:relationship) }
let!(:user) { create(:user) }
使用!运算符强制创建用户变量并将其存储到数据库中。否则,将延迟加载变量(仅在需要时)。这就是为什么它在数据库中不可用的原因pass
:在spec中遵循_id
,然后再次运行它
describe '#create' do
it "should require logged-in user to create relationship" do
post :create, followed_id: user.id
expect{
Relationship.create
}.to change(Relationship, :count).by(1)
redirect_to root_path
end
结束结果如下:
describe '#create' do
let!(:followed) { create(:user) }
it "should require logged-in user to create relationship" do
expect{
post :create, followed_id: followed.id
}.to change(Relationship, :count).by(1)
redirect_to root_path
end
end
您没有发布
followed_id
参数。我的意思是,在控制器规范中,当您发出post请求时,您的期望似乎是手动创建一个关系,然后检查计数。这实际上不是在测试你的控制器。@AaronWashburn你能解释一下你的评论吗,也许可以用一个例子或教程。thanks@Jony,您正在调用Relationship.create,然后检查是否已创建关系。这是在测试你的模型,而不是你的控制器。如果查看销毁规范,则直接使用销毁控制器操作来更改关系计数。您希望对创建操作执行相同的操作。然后,不要忘记正确命名您的测试描述,这样其他人就可以知道您正在尝试做什么。
describe '#create' do
it "should require logged-in user to create relationship" do
post :create, followed_id: user.id
expect{
Relationship.create
}.to change(Relationship, :count).by(1)
redirect_to root_path
end
describe '#create' do
let!(:followed) { create(:user) }
it "should require logged-in user to create relationship" do
expect{
post :create, followed_id: followed.id
}.to change(Relationship, :count).by(1)
redirect_to root_path
end
end