我的rspec中有以下代码(目的是测试控制器功能是否正常工作)。
require 'rails_helper'
describe CollaborationsController do
include TestFactories
before do
# @user = create(:user)
@user = authenticated_user
# @wiki = create(:wiki, user: @user)
@wiki = authenticated_wiki
sign_in @user
end
describe "#create" do
expect (@user.collaborations.find_by_wiki_id(@wiki.id)).to be_nil
post :create, {wiki_id: @wiki.id}
expect(@user.collaborations.find_by_wiki_id(@wiki.id)).not_to be_nil
end
describe "#destroy" do
expect (@user.collaborations).to eq (0)
post :create, {wiki_id: @wiki.id}
expect (@user.collaborations).to eq (1)
delete :destroy, {wiki_id: @wiki.id, id: collaborations.id}
expect(@user.collaborations.find_by_wiki_id(@wiki.id)).not_to be_nil
end
end
def authenticated_user
user = User.new(email: "email#{rand}@fake.com", password: 'password')
user.skip_confirmation!
user.save
user
end
def authenticated_wiki
wiki = Wiki.new(title: "Dit is de title", body: 'password')
wiki.save
wiki
end
当我运行它时,我收到以下错误:
undefined method `collaborations' for nil:NilClass
这对我来说有点奇怪,因为当我在控制台中尝试关系时一切正常。
u = User.first u.collaborations给出了这个fe
collaboration Load (0.3ms) SELECT "collaborations".* FROM "collaborations" WHERE "collaborations"."user_id" = ? [["user_id", 1]]
=> #<ActiveRecord::Associations::CollectionProxy [#<Collaboration id: 18, user_id: 1, wiki_id: 1, created_at: "2015-02-26 08:54:36", updated_at: "2015-02-26 08:54:36">, #<Collaboration id: 19, user_id: 1, wiki_id: 1, created_at: "2015-02- 26 09:07:19", updated_at: "2015-02-26 09:07:19">]>
2.1.5 :003 >
关于我在这里做错什么的快速思考?
答案 0 :(得分:1)
我担心您的代码无效。您将测试代码放在describe
块中,但它应该包含it
。尝试格式化:
describe "#create" do
expect (@user.collaborations.find_by_wiki_id(@wiki.id)).to be_nil
post :create, {wiki_id: @wiki.id}
expect(@user.collaborations.find_by_wiki_id(@wiki.id)).not_to be_nil
end
describe "#destroy" do
expect (@user.collaborations).to eq (0)
post :create, {wiki_id: @wiki.id}
expect (@user.collaborations).to eq (1)
delete :destroy, {wiki_id: @wiki.id, id: collaborations.id}
expect(@user.collaborations.find_by_wiki_id(@wiki.id)).not_to be_nil
end
像这样:
describe "#create" do
it "sets the collaborations" do
expect (@user.collaborations.find_by_wiki_id(@wiki.id)).to be_nil
post :create, {wiki_id: @wiki.id}
expect(@user.collaborations.find_by_wiki_id(@wiki.id)).not_to be_nil
do
end
describe "#destroy" do
it "destroys collaborator" do
expect (@user.collaborations).to eq (0)
post :create, {wiki_id: @wiki.id}
expect (@user.collaborations).to eq (1)
delete :destroy, {wiki_id: @wiki.id, id: collaborations.id}
expect(@user.collaborations.find_by_wiki_id(@wiki.id)).not_to be_nil
end
end
有时缺少it
会导致奇怪的行为和误导性的错误消息。
希望这能解决你的问题!
答案 1 :(得分:0)
尝试使用before(:each)
此外,我想在describe block中执行类似let(:user){ authenticated_user }
的操作。
在一个it
块中执行期望