客户参数验证的功能测试 - Rspec / Capybara

时间:2014-07-03 02:54:13

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

我在我的控制器中添加了客户验证,如

def customer_create
  if params[:api_key].present?
    ## Create Customer
  else
    ## Render Error Message in Json format
  end
end

如何为上述方法编写Rspec测试?

提前致谢

1 个答案:

答案 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