[英]How do I test association in rails controller with rspec?
我有一個包含很多評論的文章模型,該評論屬於一篇文章。 這是我的comment_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請將Gemfile
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
的句子是不自然的,請修改句子。 :-(
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.