我在我的控制器中添加了客户验证,如
def customer_create
if params[:api_key].present?
## Create Customer
else
## Render Error Message in Json format
end
end
如何为上述方法编写Rspec测试?
提前致谢
答案 0 :(得分:1)
大概是customer_create
来自您的控制器的create
动作?
所以简单地测试一下这个动作就足够了。
describe CustomersController do
it "creates customer if :api_key is present` do
post :create, api_key: "present key", customer_attributes
expect(Customer.count).to eq 1
end
it "does not create customer if :api_key is absent` do
json_error = {
key1: 'value1',
key2: 'value2'
}.to_json
post :create, customer_attributes
expect(response.body).to eq json_error
end
end
如果设置了参数,则可以直接测试该方法。
describe CustomersController do
it "creates customer if :api_key is present' do
controller.params[:api_key] = 'present key'
controller.params.merge!(customer_attributes)
controller.customer_create
expect(Customer.count).to eq 1
end
end
两个示例都假设客户属性哈希存储在变量customer_attributes