在制造商 gem 和 rspec 中传递变量
Pass variables in fabricator gem and rspec
如何通过在 rspec 中传递用作瞬态的变量来创建用户?我做错了什么?
controller_tests_spec.rb
describe "GET index" do
context "with admin user_role" do
before(:each) do
set_current_admin
todo_list1 = Fabricate(:todo_list)
todo_list2 = Fabricate(:todo_list)
get :index
end
it "redirects to the todo lists path" do
expect(response).to redirect_to todo_lists_path
end
end
end
/support/macros.rb
def set_current_admin(user=nil)
session[:user_id] = (user || Fabricate(:user, role: "admin")).id
end
制造商
# user_fabricator.rb
Fabricator(:user) do
email {Faker::Internet.email}
password 'password'
first_name {Faker::Name.first_name}
last_name {Faker::Name.last_name}
transient :role
user_role {Fabricate(:user_role, role: :role)}
end
# user_role_fabricator.rb
Fabricator(:user_role) do
role
end
所有处理过的值(包括瞬态值)都可以通过在每个字段被制造时传递到每个字段的 attrs 散列来获得。我修改了你的制造者来做我认为你期望的事情。
我将 :user_role
中的角色字段默认为 "member"。您拥有它的方式将尝试扩展以使用另一个名为 role
的制造商,我认为这不是您想要的。
# user_fabricator.rb
Fabricator(:user) do
email {Faker::Internet.email}
password 'password'
first_name {Faker::Name.first_name}
last_name {Faker::Name.last_name}
transient :role
user_role { |attrs| Fabricate(:user_role, role: attrs[:role]) }
end
# user_role_fabricator.rb
Fabricator(:user_role) do
role 'member'
end
如何通过在 rspec 中传递用作瞬态的变量来创建用户?我做错了什么?
controller_tests_spec.rb
describe "GET index" do
context "with admin user_role" do
before(:each) do
set_current_admin
todo_list1 = Fabricate(:todo_list)
todo_list2 = Fabricate(:todo_list)
get :index
end
it "redirects to the todo lists path" do
expect(response).to redirect_to todo_lists_path
end
end
end
/support/macros.rb
def set_current_admin(user=nil)
session[:user_id] = (user || Fabricate(:user, role: "admin")).id
end
制造商
# user_fabricator.rb
Fabricator(:user) do
email {Faker::Internet.email}
password 'password'
first_name {Faker::Name.first_name}
last_name {Faker::Name.last_name}
transient :role
user_role {Fabricate(:user_role, role: :role)}
end
# user_role_fabricator.rb
Fabricator(:user_role) do
role
end
所有处理过的值(包括瞬态值)都可以通过在每个字段被制造时传递到每个字段的 attrs 散列来获得。我修改了你的制造者来做我认为你期望的事情。
我将 :user_role
中的角色字段默认为 "member"。您拥有它的方式将尝试扩展以使用另一个名为 role
的制造商,我认为这不是您想要的。
# user_fabricator.rb
Fabricator(:user) do
email {Faker::Internet.email}
password 'password'
first_name {Faker::Name.first_name}
last_name {Faker::Name.last_name}
transient :role
user_role { |attrs| Fabricate(:user_role, role: attrs[:role]) }
end
# user_role_fabricator.rb
Fabricator(:user_role) do
role 'member'
end