Rspec测试控制器操作创建逻辑

时间:2015-11-26 02:26:23

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

我正在试图找出测试我的控制器的逻辑。正如您在我的控制器中看到的那样,如果通过电话号码找到客户,它应该呈现客户显示页面,如果通过电话号码找不到客户,那么它应该呈现创建页面。

我正在使用rspec和factorygirl。

我的思维过程是通过构建客户,为其分配特定ID:999999和电话号码来构建测试。

然后做一个帖子:使用相同的电话号码为客户创建。这应该将响应返回为customers / id。

当我的代码通过测试时,当我更改帖子时:创建客户电话号码,它仍然通过。我不知道我做错了什么,但这似乎不对。

控制器:

def create        
   if @customer = Customer.find_by(phone: customer_params[:phone])
     redirect_to @customer
   else
     @customer = Customer.new(customer_params)
     if @customer.save
       redirect_to @customer, notice: "Customer was successfully saved"
     else
       render 'new', notice: "Customer was unsuccessfully saved"
     end
   end
 end

控制器规格#1(传递):

it "redirects to the #show/id path if it is an existing customer" do
   customer = build(:customer)
   customer[:id] = 999999
   customer[:phone] = "999"

   post :create, customer: attributes_for(:customer, phone: "999")            
   expect(response).to redirect_to(:action => :show, :id => assigns(:customer).id)
end

控制器规格#2(更改帖子:创建客户电话)(传递):

it "redirects to the #show/id path if it is an existing customer" do
   customer = build(:customer)
   customer[:id] = 99999
   customer[:phone] = "999"

   post :create, customer: attributes_for(:customer, phone: "939")
   expect(response).to redirect_to(:action => :show, :id => assigns(:customer).id)
end

1 个答案:

答案 0 :(得分:0)

在这两种情况下,当找到客户或创建新客户时,response将是redirect_to,这就是您的测试通过的原因。请注意,由于您在测试中使用build,因此不会将客户保存在数据库中,因此您的测试始终会创建新的customer,并且Customer.find_by(phone: customer_params[:phone])始终在评估{{} 1}}。

测试nil操作的最佳方法是比较请求之前和之后create个实例的数量。以下是如何改进测试的方法。

Customer
相关问题