Rails测试数据库关联表

时间:2015-06-16 16:22:53

标签: ruby-on-rails testing activerecord

每个用户都可以投票支持由关联建模的帖子:每个用户has_many :voting, through: :active_vote_relationships。他们应该只允许投票一次,所以我在模式中得到unique: true

add_index "voterelationships", ["voter_id", "voted_id"], name: "index_voterelationships_on_voter_id_and_voted_id", unique: true, using: :btree

我试图通过让用户投票支持他已经投票的帖子来测试这个:

test "shouldn't be able to vote again for a post already voted for" do
  assert_no_difference '@user.postvoting.count' do
    xhr :post, voterelationships_path(voter_callsign: @user.callsign, voted_id: @post_1.id)
  end
end

我期待测试通过。相反,我得到了这个错误:

ActiveRecord::RecordNotUnique: PG::UniqueViolation: ERROR:  duplicate key value violates unique constraint "index_voterelationships_on_voter_id_and_voted_id"

似乎唯一性要求正确地防止表中的重复对,但为什么这会导致测试错误而不是传递?我认为第二次投票尝试只会被数据库拒绝。如何让测试通过?

1 个答案:

答案 0 :(得分:0)

这很正常。您应该使用assert_raises声明将引发ActiveRecord::RecordNotUnique异常。

示例:

assert_raises ActiveRecord::RecordNotUnique do
  xhr :post, voterelationships_path(voter_callsign: @user.callsign, voted_id: @post_1.id)
end