未定义的方法'person'for nil:NilClass

时间:2018-11-19 01:28:32

标签: ruby-on-rails ruby ruby-on-rails-3

我正在尝试通过学习教程来创建联系人管理器。我认为该教程缺少某些部分,在编写测试时会卡住。

describe "POST #create" do
context "with valid params" do
  it "creates a new PhoneNumber" do
    expect {
      post :create, params: {phone_number: valid_attributes}, session: valid_session
    }.to change(PhoneNumber, :count).by(1)
  end

  it "redirects to the phone number's person" do
    alice = Person.create(first_name: 'Alice', last_name: 'Smith')
    valid_attributes = {number: '555-8888', person_id: alice.id}
    post :create, params: {:phone_number => valid_attributes}, session: valid_session
    expect(response).to redirect_to(@phone_number.person)
  end
 end
end

我的代码给出以下错误

   undefined method `person' for nil: NilClass

据我了解,我需要以某种方式初始化@phone_number。由于我是Rails的新手,所以我无法弄清楚。

任何帮助都会很好。

2 个答案:

答案 0 :(得分:1)

也许尝试根据用于创建电话号码的属性来查找:

@phone_number = PhoneNumber.find_by(number: '555-8888')
expect(response).to redirect_to(@phone_number.person)

答案 1 :(得分:1)

您可以这样做:

class InterpreterTypeA : InterpreterGeneral {
public:
    void saveContainer(ContainerTypeA* cont) {
        containerA = cont;
        container = cont;
    }
    void doSomething() {
        containerA->doSomethingA();
    }
private:
    ContainerTypeA* containerA;
};