【问题标题】:NoMethodError: undefined method `to_sym' for {:factory=>:user}:HashNoMethodError: {:factory=>:user}:Hash 的未定义方法 `to_sym'
【发布时间】:2014-04-14 13:57:13
【问题描述】:

我在字符工厂上调用 create 时出错

    factory :user do |f|
        f.sequence(:email) { |n| "foo#{n}@example.com" }
        f.password "password"       
  end

    factory :character do |f|
        f.name "testcharone"
        f.race "human"
    after(:create) { |character| character.init("fighter")}
    association factory: :user
  end

错误:

NoMethodError:
       undefined method `to_sym' for {:factory=>:user}:Hash

谁能看出问题所在?

此测试需要 16 分钟才能完成,而其他类似的测试需要 5-10 分钟

describe Character do   
    let(:character) { FactoryGirl.create :character}

  describe "#add_units" do  
        context "when unit doesnt exist beforehand" do          
        it "it create a new member" do
            expect(character.owns.count).to eq(0)
            character.add_units("character", "Archer" => 1)
            expect(character.owns.count).to eq(1)
            expect(character.owns.first.amount).to eq(1)
        end
    end

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 rspec factory-bot


    【解决方案1】:

    factory :character

    替换

     association factory: :user
    

     association :user
    

    在这种情况下,您只需传递工厂名称,即:user,而不是哈希factory: :user

    【讨论】:

    • 啊解决了错误,但现在我的 rspec 需要 15 分钟才能完成一个非常简单的测试
    • 应该是f.association :user而不是association :user
    • @RajarshiDas 这不是强制性的。但出于一致性目的是的。
    • @manis 这取决于您正在运行的示例。测试一个例子,看看它需要多少时间。例如:rspec spec/path/to/some_spec.rb -e "My Example" 你有一个例子it "My Example"
    【解决方案2】:

    你的工厂应该如下所示

    希望你也应该为user 建立一个工厂

    factory :character do |f|
       f.name "testcharone"
       f.race "human"
       f.association :author, factory: :user
       after(:create) { |character| character.init("fighter")}
    end
    

     factory :character do 
       name "testcharone"
       race "human"
       association :user
       after(:create) { |character| character.init("fighter")}
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-13
      • 2011-01-17
      • 1970-01-01
      相关资源
      最近更新 更多