所以我有User
has_many :comments
。
在我的Comments#Index
中,我有这个:
def index
@comments = current_user.comments
end
在我Rspec.config...
的{{1}}区块内,我有这个:
rails_helper.rb
我的 # Add Config info for Devise
config.include Devise::TestHelpers, type: :controller
看起来像这样:
comments_controller_spec.rb
这是我的 describe 'GET #index' do
it "populates an array of comments that belong to a user" do
user = create(:user)
node = create(:node)
comment1 = create(:comment, node: node, user: user)
comment2 = create(:comment, node: node, user: user)
get :index, { node_id: node }
expect(assigns(:comments)).to match_array([comment1, comment2])
end
it "renders the :index template"
end
工厂:
Users.rb
这是我的FactoryGirl.define do
factory :user do
association :family_tree
first_name { Faker::Name.first_name }
last_name { Faker::Name.last_name }
email { Faker::Internet.email }
password "password123"
password_confirmation "password123"
bio { Faker::Lorem.paragraph }
invitation_relation { Faker::Lorem.word }
# required if the Devise Confirmable module is used
confirmed_at Time.now
gender 1
end
end
工厂:
Comments
这是我现在得到的错误:
FactoryGirl.define do
factory :comment do
association :node
message { Faker::Lorem.sentence }
factory :invalid_comment do
message nil
end
end
end
思想?
答案 0 :(得分:1)
您需要先登录:
describe 'GET #index' do
let(:user) { create(:user) }
let(:node) { create(:node) }
let(:comment1) { create(:comment, node: node, user: user) }
let(:comment2) { create(:comment, node: node, user: user) }
before do
@request.env["devise.mapping"] = Devise.mappings[:user]
sign_in user
end
it "populates an array of comments that belong to a user" do
get :index, { node_id: node }
expect(assigns(:comments)).to match_array [comment1, comment2]
end
end
您还可以使用以下代码在spec/support
目录中创建模块:
module SpecAuthentication
def login_user
@request.env["devise.mapping"] = Devise.mappings[:user]
@user = FactoryGirl.create :user
sign_in @user
end
end
并将其包含在RSpec.configure
块中:
config.include SpecAuthentication
现在,您可以在规范中调用login_user
方法:
describe 'GET #index' do
let(:node) { create(:node) }
let(:comment1) { create(:comment, node: node, user: @user) }
let(:comment2) { create(:comment, node: node, user: @user) }
before { login_user }
it "populates an array of comments that belong to a user" do
get :index, { node_id: node }
expect(assigns(:comments)).to match_array [comment1, comment2]
end
end
<强>更新强>
您可以在支持文件(configure
)中添加spec/rails_helper.rb
块,而不是将模块包含在configure
文件的spec/support/devise.rb
块中:< / p>
module SpecAuthorization
...
end
RSpec.configure do |config|
config.include SpecAuthorization
end