如何测试 rails 控制器与 rspec 的关联?

How do I test association in rails controller with rspec?

我有一个文章模型,其中有很多评论,评论属于一篇文章。这是我为 comments_controller.rb:

创建的方法
def create
  @comment = Comment.new(comment_params)
  @comment.article_id = params[:article_id]

  @comment.save
  redirect_to article_path(@comment.article)
end

我想知道使用 rspec 测试此操作的最佳方法是什么。我想知道控制器中关联的测试方法。

谢谢各位专家

您可以使用 assigns 方法在您的测试中访问您的评论对象:

describe CommentsController, type: :controller
  let(:comment_params) {{ <correct params goes here>}}
  let(:article_id) { (1..100).sample }
  let(:create!) { post :create, comment: comment_params, article_id: article_id }

  it "creates new comment" do
    expect { create! }.to change { Comment.count }.by 1
  end

  it "assigns given comment to correct article"
    create!
    expect(assigns(:comment).article_id).to eq params[:article_id]
  end
end

以上只是一个指南,您需要根据您的具体要求进行修改。

我推荐这个代码。 此代码正在使用 FactoryGirl。

factory_girl 是具有简单定义语法的固定装置替换... https://github.com/thoughtbot/factory_girl 请将 gem 'factory_girl_rails' 添加到 Gemfile

 def create
   @comment = Comment.new(comment_params)
   @comment.article_id = params[:article_id]

   if @comment.save
     redirect_to article_path(@comment.article)
   else
     redirect_to root_path, notice: "Comment successfully created" # or you want to redirect path
   end
 end

 describe "POST #create" do
   let(:article_id) { (1..100).sample }

   context 'when creation in' do
     it 'creates a new comment' do
       expect { post :create, comment: attributes_for(:comment), article_id: article_id }.to change {
        Comment.count
       }.from(0).to(1)
     end

     it 'returns same article_id' do
       post :create,  comment: attributes_for(:comment), article_id
       expect(assigns(:comment).article_id).to eq(article_id)
     end
   end

   context 'when successed in' do
     before { post :create, comment: attributes_for(:comment), article_id }

     it 'redirects article path' do
       expect(response).to redirect_to(Comment.last.article)
     end
   end

    context 'when unsuccessed in' do
     before { post :create, comment: attributes_for(:comment), article_id }

     it 'does not redirect article path' do
       expect(response).to redirect_to(root_path)
     end
   end
 end

呃,我的母语不是英语。所以如果it的句子不自然,请修改句子。 :-(