指定返回nil rspec rails

时间:2015-06-27 03:20:01

标签: ruby-on-rails rspec controller

我正在尝试在客户控制器中测试put方法。问题是assigns(:customer)总是返回nil,以便第一次测试失败。然而,第二个测试工作得很好,所以我不明白为什么第一个测试失败,因为从更新方法中的参数中检索了正确的客户。

  describe "PUT #update" do
    before :each do
      @customer = create(:customer, user: @user)
    end

    context "with valid attributes" do
    it "locates the requested customer" do
      put :update, id: @customer.id, customer: FactoryGirl.attributes_for(:customer).merge({user_id: @user.id})
      assigns(:customer).should eq @customer
    end

    it "should save customer to the database" do
      put :update, id: @customer, customer: {name: 'lorem', mail: 'lorem@gmail.com', address: 'lorem_address', phone:@customer.phone, user_id: @customer.user.id}
      @customer.reload
      expect(@customer.name).to eq 'lorem'
      expect(@customer.mail).to eq 'lorem@gmail.com'
      expect(@customer.address).to eq 'lorem_address'
    end
  end


FactoryGirl.define do
  factory :user do
    email {Faker::Internet.email}
    password {Faker::Internet.password(10)}
  end
end


FactoryGirl.define do
  factory :customer do
    association :user
    name Faker::Name.name
    sequence(:mail) {|i| "example#{i}@example.com"}
    address Faker::Address.street_address
    phone Faker::PhoneNumber.phone_number
  end
end


def update
    debugger
    customer = Customer.find(params[:id])
    if customer.update_attributes(customers_params)
      flash[:success] = 'Customer information updated successfully'
      redirect_to customers_path
    else
      @customer = customer
      render :edit
    end
  end

由于

1 个答案:

答案 0 :(得分:4)

从此post

  

assign是一个哈希,可以在Rails测试中访问,包含所有   此时可供视图使用的实例变量......

关键字是instance variables,即以@开头的变量。

update操作修改为以下内容会使测试通过

def update
    debugger
    @customer = Customer.find(params[:id])
    if @customer.update_attributes(customers_params)
      flash[:success] = 'Customer information updated successfully'
      redirect_to customers_path
    else
      render :edit
    end
end