我在我的record_controller_test.rb中进行了一个简单的测试,该测试最初没有任何问题。
test "should create record" do
assert_difference('Record.count') do
post records_url, params: { record: { category_id: @record.category_id, user_id: @record.user_id } }
end
我必须确保创建的每个新记录都是唯一的,所以我在模型中添加了以下内容:
validates :user_id, :uniqueness => {:scope => :category_id}
现在测试失败了。我应该如何重写测试以考虑新的唯一性验证?
更新: 这是控制器代码:
def new
@record = Record.new
@users = User.all
end
def create
@record = Record.new(record_params)
respond_to do |format|
if @record.save
format.html { redirect_to @record, notice: 'Record was successfully created.' }
format.json { render :show, status: :created, location: @record }
else
format.html { render :new }
format.json { render json: @record.errors, status: :unprocessable_entity }
end
end
end
表格:
<div class="field">
<%= form.label :user_id %>
<%= form.collection_select :user_id, @users, :id, :name %>
</div>
<div class="field">
<%= form.label :category_id %>
<%= form.collection_select :category_id, @categories, :id, :category %>
</div>
<div class="actions">
<%= form.submit %>
</div>