0

我有一个需要以下字段的客户端模型:

validates :name, :address1, :city, :state, :country, :zipcode,
:contactname, :email, presence: true

现在我正在编写用于创建新客户端的测试。我使用 FactoryGirl 创建了一个客户端对象,我如何使用工厂值填充表单,而无需手动编写fill_in "field_id", with: factory.field_value每个字段,就像我已经在做的那样,如下面的代码所示。

describe "with valid information" do
  let(:client) { FactoryGirl.create(:client) }

  before(:each) do
    visit new_client_path
    fill_in "client_name", with: client.name
    fill_in "client_address1", with: client.address1
    fill_in "client_city", with: client.city
    fill_in "client_state", with: client.state
    select client.country, from: "client_country"
    fill_in "client_zipcode", with: client.zipcode
    fill_in "client_contactname", with: client.contactname
    fill_in "client_email", with: client.email
  end

  it "should create a client" do
    expect { click_button "Create Client" }.to change(Client, :count)
  end

  describe "success messages" do
    before { click_button "Create Client" }
    it { should have_content('created') }
  end
end

谢谢

4

1 回答 1

1

您的代码没有任何问题。我看到的唯一缩短它的方法是迭代一个数组:

%w(name address1 city state zipcode contactname email).each do |field|
  fill_in "client_#{field}", with: client.send(field.to_sym)
end

但这仅适用于非常简单的情况,对于一种类型的字段(如您所见,我跳过了client_country)。

因此,如何将模型属性映射到表单字段的任务并没有通用的解决方案,因为表单字段可能是不同的类型,映射可能会更复杂。

于 2012-12-17T11:13:36.300 回答