Ruby on rails 使用FactoryGirl进行控制器测试
我想测试我的用户#show controller。如何使用FactoryGirl创建要传递到控制器的测试数据 在“spec/controllers/users\u controller\u spec.rb”中: 在“spec/factories/users.rb”中 总结一下: 使用中所示的Ruby on rails 使用FactoryGirl进行控制器测试,ruby-on-rails,testing,ruby-on-rails-4,factory-bot,Ruby On Rails,Testing,Ruby On Rails 4,Factory Bot,我想测试我的用户#show controller。如何使用FactoryGirl创建要传递到控制器的测试数据 在“spec/controllers/users\u controller\u spec.rb”中: 在“spec/factories/users.rb”中 总结一下: 使用中所示的create(:user)或build(:user),而不是Factory(:user) build(:user)不会将对象保存到数据库,因此您可能需要存根控制器的查询。不过速度更快 要传递未持久化用户的id
create(:user)
或build(:user)
,而不是Factory(:user)
build(:user)
不会将对象保存到数据库,因此您可能需要存根控制器的查询。不过速度更快
要传递未持久化用户的id,您必须执行
get:show,id:user.id
而不是get:show,id:user
我下面的教程只使用工厂(:user)
,但我相信它已经过时了-使用创建(:user)
或构建(:user)
这是下一行的一个例外,您应该执行get:show,id:user.id
现在这是控制器异常。粘贴其内容。顺便说一下,如果您希望对象根本不接触数据库,请使用build_stubbed(:user),build(:user)仍将相关对象输入数据库。
describe UsersController do
describe "GET #show" do
it "assigns the requested user to @user" do
user = Factory(:user) # How do I do this using FactoryGirl?
get :show, id: user
assigns(:user).should eq(user)
end
end
end
require 'faker'
FactoryGirl.define do
factory :user do
email { Faker::Internet.email }
end
# Replace email with nil. Apparently all other attributes defer to the
# original :user factory.
factory :invalid_user do
email nil
end
end