ruby-on-rails – 我是否正确使用工厂?
发布时间:2020-12-17 03:01:07 所属栏目:百科 来源:网络整理
导读:这是我目前的测试设置: # spec/factories.rbrequire 'factory_girl'FactoryGirl.define do # Roles factory :user_role,:class = Role do name 'User' end # Users factory :user,:class = User do sequence(:email) {|n| "email#{n}@example.com" } passwo
这是我目前的测试设置:
# spec/factories.rb require 'factory_girl' FactoryGirl.define do # Roles factory :user_role,:class => Role do name 'User' end # Users factory :user,:class => User do sequence(:email) {|n| "email#{n}@example.com" } password 'password' password_confirmation 'password' name 'Yuri Userington' roles { |a| [a.association(:user_role)] } end # Instruments factory :instrument,:class => Instrument do title "Doobie Doo Instrument Title" is_valid true association :user,:factory => :user end # Sequences sequence :email do "email#{n}@factory.com" end end # spec/controllers/instruments_controller_spec.rb require 'spec_helper' describe InstrumentsController do before (:each) do @instrument = FactoryGirl.create(:instrument) @attr = FactoryGirl.attributes_for(:instrument) @user = FactoryGirl.create(:user) end describe "GET index" do it "assigns all instruments as @instruments" do instrument = Instrument.new(@attr) instrument.user = @user instrument.save! get :index assigns(:instruments).should eq([instrument]) end end end 结果是,当我运行我的测试时,我的输出中出现以下错误: Failures: 1) InstrumentsController GET index assigns all instruments as @instruments Failure/Error: @instrument = FactoryGirl.create(:instrument) ActiveRecord::RecordNotFound: Couldn't find Role with id=2 # ./app/models/user.rb:21:in `assign_role_after_sign_up' # ./spec/controllers/instruments_controller_spec.rb:24:in `block (2 levels) in <top (required)>' 基于此,似乎我的:用户工厂中的角色关联调用没有被调用 – 我在这里做错了什么?我是以完全错误的方式使用它吗? 谢谢!! 解决方法
这里有很多话要说.将您的代码与以下内容进行比较,以查看删除了多少行或单词.
FactoryGirl.define do # Sequences sequence :email do |n| "email#{n}@factory.com" end # Roles factory :user_role,:class => Role do name 'User' end # Users factory :user do email password 'password' password_confirmation 'password' name 'Yuri Userington' roles { |user| [Factory(:user_role)] } #many to many end # Instruments factory :instrument,:class => Instrument do title "Doobie Doo Instrument Title" is_valid true association :user #one-to-one or one-to-many end end 在你的测试中: describe InstrumentsController do before (:each) do @user = Factory(:user) end describe "GET index" do it "assigns all instruments as @instruments" do instrument = Factory(:instrument,:user => @user) get :index assigns(:instruments).should eq([instrument]) end end end 此外: >我个人更喜欢测试带有模拟和存根的控制器>我使用let代替实例变量和before_filter (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |