[英]assigns returns nil rspec rails
I'm trying to test the put method in a customers controller. 我正在尝试在客户控制器中测试put方法。 The problem is that assigns(:customer) always returns nil so that first test fails.
问题在于,assigns(:customer)始终返回nil,因此第一次测试失败。 The second test, however, works perfectly, so I don't see why the first test fails, since the correct customer is retrieved from the params inside the update method.
但是,第二个测试效果很好,因此我不明白为什么第一个测试失败了,因为从update方法内部的参数中检索了正确的客户。
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
Thanks 谢谢
assigns is a hash, accessible within Rails tests, containing all the instance variables that would be available to a view at this point...
Assigns是一个哈希,可在Rails测试中访问,包含此时所有可用于视图的实例变量。
The key word is instance variables
, ie variables that start with @
. 关键字是
instance variables
,即以@
开头的变量。
Modifying your update
action to the following should make your tests pass 将
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.